xref: /freebsd/contrib/ntp/ntpd/ntp_crypto.c (revision 1669d8afc64812c8d2d1d147ae1fd42ff441e1b1)
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 OPENSSL
9 #include <stdio.h>
10 #include <sys/types.h>
11 #include <sys/param.h>
12 #include <unistd.h>
13 #include <fcntl.h>
14 
15 #include "ntpd.h"
16 #include "ntp_stdlib.h"
17 #include "ntp_unixtime.h"
18 #include "ntp_string.h"
19 
20 #include "openssl/asn1_mac.h"
21 #include "openssl/bn.h"
22 #include "openssl/err.h"
23 #include "openssl/evp.h"
24 #include "openssl/pem.h"
25 #include "openssl/rand.h"
26 #include "openssl/x509v3.h"
27 
28 #ifdef KERNEL_PLL
29 #include "ntp_syscall.h"
30 #endif /* KERNEL_PLL */
31 
32 /*
33  * Extension field message format
34  *
35  * These are always signed and saved before sending in network byte
36  * order. They must be converted to and from host byte order for
37  * processing.
38  *
39  * +-------+-------+
40  * |   op  |  len  | <- extension pointer
41  * +-------+-------+
42  * |    assocID    |
43  * +---------------+
44  * |   timestamp   | <- value pointer
45  * +---------------+
46  * |   filestamp   |
47  * +---------------+
48  * |   value len   |
49  * +---------------+
50  * |               |
51  * =     value     =
52  * |               |
53  * +---------------+
54  * | signature len |
55  * +---------------+
56  * |               |
57  * =   signature   =
58  * |               |
59  * +---------------+
60  *
61  * The CRYPTO_RESP bit is set to 0 for requests, 1 for responses.
62  * Requests carry the association ID of the receiver; responses carry
63  * the association ID of the sender. Some messages include only the
64  * operation/length and association ID words and so have length 8
65  * octets. Ohers include the value structure and associated value and
66  * signature fields. These messages include the timestamp, filestamp,
67  * value and signature words and so have length at least 24 octets. The
68  * signature and/or value fields can be empty, in which case the
69  * respective length words are zero. An empty value with nonempty
70  * signature is syntactically valid, but semantically questionable.
71  *
72  * The filestamp represents the time when a cryptographic data file such
73  * as a public/private key pair is created. It follows every reference
74  * depending on that file and serves as a means to obsolete earlier data
75  * of the same type. The timestamp represents the time when the
76  * cryptographic data of the message were last signed. Creation of a
77  * cryptographic data file or signing a message can occur only when the
78  * creator or signor is synchronized to an authoritative source and
79  * proventicated to a trusted authority.
80  *
81  * Note there are four conditions required for server trust. First, the
82  * public key on the certificate must be verified, which involves a
83  * number of format, content and consistency checks. Next, the server
84  * identity must be confirmed by one of four schemes: private
85  * certificate, IFF scheme, GQ scheme or certificate trail hike to a
86  * self signed trusted certificate. Finally, the server signature must
87  * be verified.
88  */
89 /*
90  * Cryptodefines
91  */
92 #define TAI_1972	10	/* initial TAI offset (s) */
93 #define MAX_LEAP	100	/* max UTC leapseconds (s) */
94 #define VALUE_LEN	(6 * 4) /* min response field length */
95 #define YEAR		(60 * 60 * 24 * 365) /* seconds in year */
96 
97 /*
98  * Global cryptodata in host byte order
99  */
100 u_int32	crypto_flags = 0x0;	/* status word */
101 u_int	sys_tai;		/* current UTC offset from TAI */
102 
103 /*
104  * Global cryptodata in network byte order
105  */
106 struct cert_info *cinfo = NULL;	/* certificate info/value */
107 struct value hostval;		/* host value */
108 struct value pubkey;		/* public key */
109 struct value tai_leap;		/* leapseconds table */
110 
111 /*
112  * Private cryptodata in host byte order
113  */
114 static char *passwd = NULL;	/* private key password */
115 static EVP_PKEY *host_pkey = NULL; /* host key */
116 static EVP_PKEY *sign_pkey = NULL; /* sign key */
117 static EVP_PKEY *iffpar_pkey = NULL; /* IFF parameters */
118 static EVP_PKEY	*gqpar_pkey = NULL; /* GQ parameters */
119 static EVP_PKEY	*mvpar_pkey = NULL; /* MV parameters */
120 static const EVP_MD *sign_digest = NULL; /* sign digest */
121 static u_int sign_siglen;	/* sign key length */
122 static char *rand_file = NULL;	/* random seed file */
123 static char *host_file = NULL;	/* host key file */
124 static char *sign_file = NULL;	/* sign key file */
125 static char *iffpar_file = NULL; /* IFF parameters file */
126 static char *gqpar_file = NULL;	/* GQ parameters file */
127 static char *mvpar_file = NULL;	/* MV parameters file */
128 static char *cert_file = NULL;	/* certificate file */
129 static char *leap_file = NULL;	/* leapseconds file */
130 static tstamp_t if_fstamp = 0;	/* IFF file stamp */
131 static tstamp_t gq_fstamp = 0;	/* GQ file stamp */
132 static tstamp_t mv_fstamp = 0;	/* MV file stamp */
133 
134 /*
135  * Cryptotypes
136  */
137 static	int	crypto_verify	P((struct exten *, struct value *,
138 				    struct peer *));
139 static	int	crypto_encrypt	P((struct exten *, struct value *,
140 				    keyid_t *));
141 static	int	crypto_alice	P((struct peer *, struct value *));
142 static	int	crypto_alice2	P((struct peer *, struct value *));
143 static	int	crypto_alice3	P((struct peer *, struct value *));
144 static	int	crypto_bob	P((struct exten *, struct value *));
145 static	int	crypto_bob2	P((struct exten *, struct value *));
146 static	int	crypto_bob3	P((struct exten *, struct value *));
147 static	int	crypto_iff	P((struct exten *, struct peer *));
148 static	int	crypto_gq	P((struct exten *, struct peer *));
149 static	int	crypto_mv	P((struct exten *, struct peer *));
150 static	u_int	crypto_send	P((struct exten *, struct value *));
151 static	tstamp_t crypto_time	P((void));
152 static	u_long	asn2ntp		P((ASN1_TIME *));
153 static	struct cert_info *cert_parse P((u_char *, u_int, tstamp_t));
154 static	int	cert_sign	P((struct exten *, struct value *));
155 static	int	cert_valid	P((struct cert_info *, EVP_PKEY *));
156 static	int	cert_install	P((struct exten *, struct peer *));
157 static	void	cert_free	P((struct cert_info *));
158 static	EVP_PKEY *crypto_key	P((char *, tstamp_t *));
159 static	int	bighash		P((BIGNUM *, BIGNUM *));
160 static	struct cert_info *crypto_cert P((char *));
161 static	void	crypto_tai	P((char *));
162 
163 #ifdef SYS_WINNT
164 int
165 readlink(char * link, char * file, int len) {
166 	return (-1);
167 }
168 #endif
169 
170 /*
171  * session_key - generate session key
172  *
173  * This routine generates a session key from the source address,
174  * destination address, key ID and private value. The value of the
175  * session key is the MD5 hash of these values, while the next key ID is
176  * the first four octets of the hash.
177  *
178  * Returns the next key ID
179  */
180 keyid_t
181 session_key(
182 	struct sockaddr_storage *srcadr, /* source address */
183 	struct sockaddr_storage *dstadr, /* destination address */
184 	keyid_t	keyno,		/* key ID */
185 	keyid_t	private,	/* private value */
186 	u_long	lifetime 	/* key lifetime */
187 	)
188 {
189 	EVP_MD_CTX ctx;		/* message digest context */
190 	u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
191 	keyid_t	keyid;		/* key identifer */
192 	u_int32	header[10];	/* data in network byte order */
193 	u_int	hdlen, len;
194 
195 	/*
196 	 * Generate the session key and key ID. If the lifetime is
197 	 * greater than zero, install the key and call it trusted.
198 	 */
199 	hdlen = 0;
200 	switch(srcadr->ss_family) {
201 	case AF_INET:
202 		header[0] = ((struct sockaddr_in *)srcadr)->sin_addr.s_addr;
203 		header[1] = ((struct sockaddr_in *)dstadr)->sin_addr.s_addr;
204 		header[2] = htonl(keyno);
205 		header[3] = htonl(private);
206 		hdlen = 4 * sizeof(u_int32);
207 		break;
208 	case AF_INET6:
209 		memcpy(&header[0], &GET_INADDR6(*srcadr),
210 		    sizeof(struct in6_addr));
211 		memcpy(&header[4], &GET_INADDR6(*dstadr),
212 		    sizeof(struct in6_addr));
213 		header[8] = htonl(keyno);
214 		header[9] = htonl(private);
215 		hdlen = 10 * sizeof(u_int32);
216 		break;
217 	}
218 	EVP_DigestInit(&ctx, EVP_md5());
219 	EVP_DigestUpdate(&ctx, (u_char *)header, hdlen);
220 	EVP_DigestFinal(&ctx, dgst, &len);
221 	memcpy(&keyid, dgst, 4);
222 	keyid = ntohl(keyid);
223 	if (lifetime != 0) {
224 		MD5auth_setkey(keyno, dgst, len);
225 		authtrust(keyno, lifetime);
226 	}
227 #ifdef DEBUG
228 	if (debug > 1)
229 		printf(
230 		    "session_key: %s > %s %08x %08x hash %08x life %lu\n",
231 		    stoa(srcadr), stoa(dstadr), keyno,
232 		    private, keyid, lifetime);
233 #endif
234 	return (keyid);
235 }
236 
237 
238 /*
239  * make_keylist - generate key list
240  *
241  * This routine constructs a pseudo-random sequence by repeatedly
242  * hashing the session key starting from a given source address,
243  * destination address, private value and the next key ID of the
244  * preceeding session key. The last entry on the list is saved along
245  * with its sequence number and public signature.
246  */
247 void
248 make_keylist(
249 	struct peer *peer,	/* peer structure pointer */
250 	struct interface *dstadr /* interface */
251 	)
252 {
253 	EVP_MD_CTX ctx;		/* signature context */
254 	tstamp_t tstamp;	/* NTP timestamp */
255 	struct autokey *ap;	/* autokey pointer */
256 	struct value *vp;	/* value pointer */
257 	keyid_t	keyid = 0;	/* next key ID */
258 	keyid_t	cookie;		/* private value */
259 	u_long	lifetime;
260 	u_int	len;
261 	int	i;
262 
263 	/*
264 	 * Allocate the key list if necessary.
265 	 */
266 	tstamp = crypto_time();
267 	if (peer->keylist == NULL)
268 		peer->keylist = emalloc(sizeof(keyid_t) *
269 		    NTP_MAXSESSION);
270 
271 	/*
272 	 * Generate an initial key ID which is unique and greater than
273 	 * NTP_MAXKEY.
274 	 */
275 	while (1) {
276 		keyid = (u_long)RANDOM & 0xffffffff;
277 		if (keyid <= NTP_MAXKEY)
278 			continue;
279 		if (authhavekey(keyid))
280 			continue;
281 		break;
282 	}
283 
284 	/*
285 	 * Generate up to NTP_MAXSESSION session keys. Stop if the
286 	 * next one would not be unique or not a session key ID or if
287 	 * it would expire before the next poll. The private value
288 	 * included in the hash is zero if broadcast mode, the peer
289 	 * cookie if client mode or the host cookie if symmetric modes.
290 	 */
291 	lifetime = min(sys_automax, (unsigned long) NTP_MAXSESSION * (1 <<(peer->kpoll)));
292 	if (peer->hmode == MODE_BROADCAST)
293 		cookie = 0;
294 	else
295 		cookie = peer->pcookie;
296 	for (i = 0; i < NTP_MAXSESSION; i++) {
297 		peer->keylist[i] = keyid;
298 		peer->keynumber = i;
299 		keyid = session_key(&dstadr->sin, &peer->srcadr, keyid,
300 		    cookie, lifetime);
301 		lifetime -= 1 << peer->kpoll;
302 		if (auth_havekey(keyid) || keyid <= NTP_MAXKEY ||
303 		    lifetime <= (unsigned long)(1 << (peer->kpoll)))
304 			break;
305 	}
306 
307 	/*
308 	 * Save the last session key ID, sequence number and timestamp,
309 	 * then sign these values for later retrieval by the clients. Be
310 	 * careful not to use invalid key media. Use the public values
311 	 * timestamp as filestamp.
312 	 */
313 	vp = &peer->sndval;
314 	if (vp->ptr == NULL)
315 		vp->ptr = emalloc(sizeof(struct autokey));
316 	ap = (struct autokey *)vp->ptr;
317 	ap->seq = htonl(peer->keynumber);
318 	ap->key = htonl(keyid);
319 	vp->tstamp = htonl(tstamp);
320 	vp->fstamp = hostval.tstamp;
321 	vp->vallen = htonl(sizeof(struct autokey));
322 	vp->siglen = 0;
323 	if (vp->tstamp != 0) {
324 		if (vp->sig == NULL)
325 			vp->sig = emalloc(sign_siglen);
326 		EVP_SignInit(&ctx, sign_digest);
327 		EVP_SignUpdate(&ctx, (u_char *)vp, 12);
328 		EVP_SignUpdate(&ctx, vp->ptr, sizeof(struct autokey));
329 		if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
330 			vp->siglen = htonl(len);
331 		else
332 			msyslog(LOG_ERR, "make_keys %s\n",
333 			    ERR_error_string(ERR_get_error(), NULL));
334 		peer->flags |= FLAG_ASSOC;
335 	}
336 #ifdef DEBUG
337 	if (debug)
338 		printf("make_keys: %d %08x %08x ts %u fs %u poll %d\n",
339 		    ntohl(ap->seq), ntohl(ap->key), cookie,
340 		    ntohl(vp->tstamp), ntohl(vp->fstamp), peer->kpoll);
341 #endif
342 }
343 
344 
345 /*
346  * crypto_recv - parse extension fields
347  *
348  * This routine is called when the packet has been matched to an
349  * association and passed sanity, format and MAC checks. We believe the
350  * extension field values only if the field has proper format and
351  * length, the timestamp and filestamp are valid and the signature has
352  * valid length and is verified. There are a few cases where some values
353  * are believed even if the signature fails, but only if the proventic
354  * bit is not set.
355  */
356 int
357 crypto_recv(
358 	struct peer *peer,	/* peer structure pointer */
359 	struct recvbuf *rbufp	/* packet buffer pointer */
360 	)
361 {
362 	const EVP_MD *dp;	/* message digest algorithm */
363 	u_int32	*pkt;		/* receive packet pointer */
364 	struct autokey *ap, *bp; /* autokey pointer */
365 	struct exten *ep, *fp;	/* extension pointers */
366 	int	has_mac;	/* length of MAC field */
367 	int	authlen;	/* offset of MAC field */
368 	associd_t associd;	/* association ID */
369 	tstamp_t tstamp = 0;	/* timestamp */
370 	tstamp_t fstamp = 0;	/* filestamp */
371 	u_int	len;		/* extension field length */
372 	u_int	code;		/* extension field opcode */
373 	u_int	vallen = 0;	/* value length */
374 	X509	*cert;		/* X509 certificate */
375 	char	statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
376 	keyid_t	cookie;		/* crumbles */
377 	int	rval = XEVNT_OK;
378 	u_char	*ptr;
379 	u_int32 temp32;
380 #ifdef KERNEL_PLL
381 #if NTP_API > 3
382 	struct timex ntv;	/* kernel interface structure */
383 #endif /* NTP_API */
384 #endif /* KERNEL_PLL */
385 
386 	/*
387 	 * Initialize. Note that the packet has already been checked for
388 	 * valid format and extension field lengths. First extract the
389 	 * field length, command code and association ID in host byte
390 	 * order. These are used with all commands and modes. Then check
391 	 * the version number, which must be 2, and length, which must
392 	 * be at least 8 for requests and VALUE_LEN (24) for responses.
393 	 * Packets that fail either test sink without a trace. The
394 	 * association ID is saved only if nonzero.
395 	 */
396 	authlen = LEN_PKT_NOMAC;
397 	while ((has_mac = rbufp->recv_length - authlen) > MAX_MAC_LEN) {
398 		pkt = (u_int32 *)&rbufp->recv_pkt + authlen / 4;
399 		ep = (struct exten *)pkt;
400 		code = ntohl(ep->opcode) & 0xffff0000;
401 		len = ntohl(ep->opcode) & 0x0000ffff;
402 		associd = (associd_t) ntohl(pkt[1]);
403 		rval = XEVNT_OK;
404 #ifdef DEBUG
405 		if (debug)
406 			printf(
407 			    "crypto_recv: flags 0x%x ext offset %d len %u code %x assocID %d\n",
408 			    peer->crypto, authlen, len, code >> 16,
409 			    associd);
410 #endif
411 
412 		/*
413 		 * Check version number and field length. If bad,
414 		 * quietly ignore the packet.
415 		 */
416 		if (((code >> 24) & 0x3f) != CRYPTO_VN || len < 8 ||
417 		    (len < VALUE_LEN && (code & CRYPTO_RESP))) {
418 			sys_unknownversion++;
419 			code |= CRYPTO_ERROR;
420 		}
421 
422 		/*
423 		 * Little vulnerability bandage here. If a perp tosses a
424 		 * fake association ID over the fence, we better toss it
425 		 * out. Only the first one counts.
426 		 */
427 		if (code & CRYPTO_RESP) {
428 			if (peer->assoc == 0)
429 				peer->assoc = associd;
430 			else if (peer->assoc != associd)
431 				code |= CRYPTO_ERROR;
432 		}
433 		if (len >= VALUE_LEN) {
434 			tstamp = ntohl(ep->tstamp);
435 			fstamp = ntohl(ep->fstamp);
436 			vallen = ntohl(ep->vallen);
437 		}
438 		switch (code) {
439 
440 		/*
441 		 * Install status word, host name, signature scheme and
442 		 * association ID. In OpenSSL the signature algorithm is
443 		 * bound to the digest algorithm, so the NID completely
444 		 * defines the signature scheme. Note the request and
445 		 * response are identical, but neither is validated by
446 		 * signature. The request is processed here only in
447 		 * symmetric modes. The server name field would be
448 		 * useful to implement access controls in future.
449 		 */
450 		case CRYPTO_ASSOC:
451 
452 			/*
453 			 * Pass the extension field to the transmit
454 			 * side.
455 			 */
456 			fp = emalloc(len);
457 			memcpy(fp, ep, len);
458 			temp32 = CRYPTO_RESP;
459 			fp->opcode |= htonl(temp32);
460 			peer->cmmd = fp;
461 			/* fall through */
462 
463 		case CRYPTO_ASSOC | CRYPTO_RESP:
464 
465 			/*
466 			 * Discard the message if it has already been
467 			 * stored or the server is not synchronized.
468 			 */
469 			if (peer->crypto || !fstamp)
470 				break;
471 
472 			if (len < VALUE_LEN + vallen) {
473 				rval = XEVNT_LEN;
474 				break;
475 			}
476 
477 			/*
478 			 * Check the identity schemes are compatible. If
479 			 * the client has PC, the server must have PC,
480 			 * in which case the server public key and
481 			 * identity are presumed valid, so we skip the
482 			 * certificate and identity exchanges and move
483 			 * immediately to the cookie exchange which
484 			 * confirms the server signature. If the client
485 			 * has IFF or GC or both, the server must have
486 			 * the same one or both. Otherwise, the default
487 			 * TC scheme is used.
488 			 */
489 			if (crypto_flags & CRYPTO_FLAG_PRIV) {
490 				if (!(fstamp & CRYPTO_FLAG_PRIV))
491 					rval = XEVNT_KEY;
492 				else
493 					fstamp |= CRYPTO_FLAG_VALID |
494 					    CRYPTO_FLAG_VRFY;
495 			} else if (crypto_flags & CRYPTO_FLAG_MASK &&
496 			    !(crypto_flags & fstamp &
497 			    CRYPTO_FLAG_MASK)) {
498 				rval = XEVNT_KEY;
499 			}
500 
501 			/*
502 			 * Discard the message if identity error.
503 			 */
504 			if (rval != XEVNT_OK)
505 				break;
506 
507 			/*
508 			 * Discard the message if the host name length
509 			 * is unreasonable or the signature digest NID
510 			 * is not supported.
511 			 */
512 			temp32 = (fstamp >> 16) & 0xffff;
513 			dp =
514 			    (const EVP_MD *)EVP_get_digestbynid(temp32);
515 			if (vallen == 0 || vallen > MAXHOSTNAME)
516 				rval = XEVNT_LEN;
517 			else if (dp == NULL)
518 				rval = XEVNT_MD;
519 			if (rval != XEVNT_OK)
520 				break;
521 
522 			/*
523 			 * Save status word, host name and message
524 			 * digest/signature type. If PC identity, be
525 			 * sure not to sign the certificate.
526 			 */
527 			if (crypto_flags & CRYPTO_FLAG_PRIV)
528 				fstamp |= CRYPTO_FLAG_SIGN;
529 			peer->crypto = fstamp;
530 			peer->digest = dp;
531 			peer->subject = emalloc(vallen + 1);
532 			memcpy(peer->subject, ep->pkt, vallen);
533 			peer->subject[vallen] = '\0';
534 			peer->issuer = emalloc(vallen + 1);
535 			strcpy(peer->issuer, peer->subject);
536 			temp32 = (fstamp >> 16) & 0xffff;
537 			sprintf(statstr,
538 			    "flags 0x%x host %s signature %s", fstamp,
539 			    peer->subject, OBJ_nid2ln(temp32));
540 			record_crypto_stats(&peer->srcadr, statstr);
541 #ifdef DEBUG
542 			if (debug)
543 				printf("crypto_recv: %s\n", statstr);
544 #endif
545 			break;
546 
547 		/*
548 		 * Decode X509 certificate in ASN.1 format and extract
549 		 * the data containing, among other things, subject
550 		 * name and public key. In the default identification
551 		 * scheme, the certificate trail is followed to a self
552 		 * signed trusted certificate.
553 		 */
554 		case CRYPTO_CERT | CRYPTO_RESP:
555 
556 			/*
557 			 * Discard the message if invalid or identity
558 			 * already confirmed.
559 			 */
560 			if (peer->crypto & CRYPTO_FLAG_VRFY)
561 				break;
562 
563 			if ((rval = crypto_verify(ep, NULL, peer)) !=
564 			    XEVNT_OK)
565 				break;
566 
567 			/*
568 			 * Scan the certificate list to delete old
569 			 * versions and link the newest version first on
570 			 * the list.
571 			 */
572 			if ((rval = cert_install(ep, peer)) != XEVNT_OK)
573 				break;
574 
575 			/*
576 			 * If we snatch the certificate before the
577 			 * server certificate has been signed by its
578 			 * server, it will be self signed. When it is,
579 			 * we chase the certificate issuer, which the
580 			 * server has, and keep going until a self
581 			 * signed trusted certificate is found. Be sure
582 			 * to update the issuer field, since it may
583 			 * change.
584 			 */
585 			if (peer->issuer != NULL)
586 				free(peer->issuer);
587 			peer->issuer = emalloc(strlen(cinfo->issuer) +
588 			    1);
589 			strcpy(peer->issuer, cinfo->issuer);
590 
591 			/*
592 			 * We plug in the public key and group key in
593 			 * the first certificate received. However, note
594 			 * that this certificate might not be signed by
595 			 * the server, so we can't check the
596 			 * signature/digest NID.
597 			 */
598 			if (peer->pkey == NULL) {
599 				ptr = (u_char *)cinfo->cert.ptr;
600 				cert = d2i_X509(NULL, &ptr,
601 				    ntohl(cinfo->cert.vallen));
602 				peer->pkey = X509_get_pubkey(cert);
603 				X509_free(cert);
604 			}
605 			peer->flash &= ~TEST10;
606 			temp32 = cinfo->nid;
607 			sprintf(statstr, "cert %s 0x%x %s (%u) fs %u",
608 			    cinfo->subject, cinfo->flags,
609 			    OBJ_nid2ln(temp32), temp32,
610 			    ntohl(ep->fstamp));
611 			record_crypto_stats(&peer->srcadr, statstr);
612 #ifdef DEBUG
613 			if (debug)
614 				printf("crypto_recv: %s\n", statstr);
615 #endif
616 			break;
617 
618 		/*
619 		 * Schnorr (IFF)identity scheme. This scheme is designed
620 		 * for use with shared secret group keys and where the
621 		 * certificate may be generated by a third party. The
622 		 * client sends a challenge to the server, which
623 		 * performs a calculation and returns the result. A
624 		 * positive result is possible only if both client and
625 		 * server contain the same secret group key.
626 		 */
627 		case CRYPTO_IFF | CRYPTO_RESP:
628 
629 			/*
630 			 * Discard the message if invalid or identity
631 			 * already confirmed.
632 			 */
633 			if (peer->crypto & CRYPTO_FLAG_VRFY)
634 				break;
635 
636 			if ((rval = crypto_verify(ep, NULL, peer)) !=
637 			    XEVNT_OK)
638 				break;
639 
640 			/*
641 			 * If the the challenge matches the response,
642 			 * the certificate public key, as well as the
643 			 * server public key, signatyre and identity are
644 			 * all verified at the same time. The server is
645 			 * declared trusted, so we skip further
646 			 * certificate stages and move immediately to
647 			 * the cookie stage.
648 			 */
649 			if ((rval = crypto_iff(ep, peer)) != XEVNT_OK)
650 				break;
651 
652 			peer->crypto |= CRYPTO_FLAG_VRFY |
653 			    CRYPTO_FLAG_PROV;
654 			peer->flash &= ~TEST10;
655 			sprintf(statstr, "iff fs %u",
656 			    ntohl(ep->fstamp));
657 			record_crypto_stats(&peer->srcadr, statstr);
658 #ifdef DEBUG
659 			if (debug)
660 				printf("crypto_recv: %s\n", statstr);
661 #endif
662 			break;
663 
664 		/*
665 		 * Guillou-Quisquater (GQ) identity scheme. This scheme
666 		 * is designed for use with public certificates carrying
667 		 * the GQ public key in an extension field. The client
668 		 * sends a challenge to the server, which performs a
669 		 * calculation and returns the result. A positive result
670 		 * is possible only if both client and server contain
671 		 * the same group key and the server has the matching GQ
672 		 * private key.
673 		 */
674 		case CRYPTO_GQ | CRYPTO_RESP:
675 
676 			/*
677 			 * Discard the message if invalid or identity
678 			 * already confirmed.
679 			 */
680 			if (peer->crypto & CRYPTO_FLAG_VRFY)
681 				break;
682 
683 			if ((rval = crypto_verify(ep, NULL, peer)) !=
684 			    XEVNT_OK)
685 				break;
686 
687 			/*
688 			 * If the the challenge matches the response,
689 			 * the certificate public key, as well as the
690 			 * server public key, signatyre and identity are
691 			 * all verified at the same time. The server is
692 			 * declared trusted, so we skip further
693 			 * certificate stages and move immediately to
694 			 * the cookie stage.
695 			 */
696 			if ((rval = crypto_gq(ep, peer)) != XEVNT_OK)
697 				break;
698 
699 			peer->crypto |= CRYPTO_FLAG_VRFY |
700 			    CRYPTO_FLAG_PROV;
701 			peer->flash &= ~TEST10;
702 			sprintf(statstr, "gq fs %u",
703 			    ntohl(ep->fstamp));
704 			record_crypto_stats(&peer->srcadr, statstr);
705 #ifdef DEBUG
706 			if (debug)
707 				printf("crypto_recv: %s\n", statstr);
708 #endif
709 			break;
710 
711 		/*
712 		 * MV
713 		 */
714 		case CRYPTO_MV | CRYPTO_RESP:
715 
716 			/*
717 			 * Discard the message if invalid or identity
718 			 * already confirmed.
719 			 */
720 			if (peer->crypto & CRYPTO_FLAG_VRFY)
721 				break;
722 
723 			if ((rval = crypto_verify(ep, NULL, peer)) !=
724 			    XEVNT_OK)
725 				break;
726 
727 			/*
728 			 * If the the challenge matches the response,
729 			 * the certificate public key, as well as the
730 			 * server public key, signatyre and identity are
731 			 * all verified at the same time. The server is
732 			 * declared trusted, so we skip further
733 			 * certificate stages and move immediately to
734 			 * the cookie stage.
735 			 */
736 			if ((rval = crypto_mv(ep, peer)) != XEVNT_OK)
737 				break;
738 
739 			peer->crypto |= CRYPTO_FLAG_VRFY |
740 			    CRYPTO_FLAG_PROV;
741 			peer->flash &= ~TEST10;
742 			sprintf(statstr, "mv fs %u",
743 			    ntohl(ep->fstamp));
744 			record_crypto_stats(&peer->srcadr, statstr);
745 #ifdef DEBUG
746 			if (debug)
747 				printf("crypto_recv: %s\n", statstr);
748 #endif
749 			break;
750 
751 		/*
752 		 * X509 certificate sign response. Validate the
753 		 * certificate signed by the server and install. Later
754 		 * this can be provided to clients of this server in
755 		 * lieu of the self signed certificate in order to
756 		 * validate the public key.
757 		 */
758 		case CRYPTO_SIGN | CRYPTO_RESP:
759 
760 			/*
761 			 * Discard the message if invalid or identity
762 			 * not confirmed.
763 			 */
764 			if (!(peer->crypto & CRYPTO_FLAG_VRFY))
765 				break;
766 
767 			if ((rval = crypto_verify(ep, NULL, peer)) !=
768 			    XEVNT_OK)
769 				break;
770 
771 			/*
772 			 * Scan the certificate list to delete old
773 			 * versions and link the newest version first on
774 			 * the list.
775 			 */
776 			if ((rval = cert_install(ep, peer)) != XEVNT_OK) 				break;
777 
778 			peer->crypto |= CRYPTO_FLAG_SIGN;
779 			peer->flash &= ~TEST10;
780 			temp32 = cinfo->nid;
781 			sprintf(statstr, "sign %s 0x%x %s (%u) fs %u",
782 			    cinfo->issuer, cinfo->flags,
783 			    OBJ_nid2ln(temp32), temp32,
784 			    ntohl(ep->fstamp));
785 			record_crypto_stats(&peer->srcadr, statstr);
786 #ifdef DEBUG
787 			if (debug)
788 				printf("crypto_recv: %s\n", statstr);
789 #endif
790 			break;
791 
792 		/*
793 		 * Cookie request in symmetric modes. Roll a random
794 		 * cookie and install in symmetric mode. Encrypt for the
795 		 * response, which is transmitted later.
796 		 */
797 		case CRYPTO_COOK:
798 
799 			/*
800 			 * Discard the message if invalid or identity
801 			 * not confirmed.
802 			 */
803 			if (!(peer->crypto & CRYPTO_FLAG_VRFY))
804 				break;
805 
806 			if ((rval = crypto_verify(ep, NULL, peer)) !=
807 			    XEVNT_OK)
808 				break;
809 
810 			/*
811 			 * Pass the extension field to the transmit
812 			 * side. If already agreed, walk away.
813 			 */
814 			fp = emalloc(len);
815 			memcpy(fp, ep, len);
816 			temp32 = CRYPTO_RESP;
817 			fp->opcode |= htonl(temp32);
818 			peer->cmmd = fp;
819 			if (peer->crypto & CRYPTO_FLAG_AGREE) {
820 				peer->flash &= ~TEST10;
821 				break;
822 			}
823 
824 			/*
825 			 * Install cookie values and light the cookie
826 			 * bit. The transmit side will pick up and
827 			 * encrypt it for the response.
828 			 */
829 			key_expire(peer);
830 			peer->cookval.tstamp = ep->tstamp;
831 			peer->cookval.fstamp = ep->fstamp;
832 			RAND_bytes((u_char *)&peer->pcookie, 4);
833 			peer->crypto &= ~CRYPTO_FLAG_AUTO;
834 			peer->crypto |= CRYPTO_FLAG_AGREE;
835 			peer->flash &= ~TEST10;
836 			sprintf(statstr, "cook %x ts %u fs %u",
837 			    peer->pcookie, ntohl(ep->tstamp),
838 			    ntohl(ep->fstamp));
839 			record_crypto_stats(&peer->srcadr, statstr);
840 #ifdef DEBUG
841 			if (debug)
842 				printf("crypto_recv: %s\n", statstr);
843 #endif
844 			break;
845 
846 		/*
847 		 * Cookie response in client and symmetric modes. If the
848 		 * cookie bit is set, the working cookie is the EXOR of
849 		 * the current and new values.
850 		 */
851 		case CRYPTO_COOK | CRYPTO_RESP:
852 
853 			/*
854 			 * Discard the message if invalid or identity
855 			 * not confirmed or signature not verified with
856 			 * respect to the cookie values.
857 			 */
858 			if (!(peer->crypto & CRYPTO_FLAG_VRFY))
859 				break;
860 
861 			if ((rval = crypto_verify(ep, &peer->cookval,
862 			    peer)) != XEVNT_OK)
863 				break;
864 
865 			/*
866 			 * Decrypt the cookie, hunting all the time for
867 			 * errors.
868 			 */
869 			if (vallen == (u_int) EVP_PKEY_size(host_pkey)) {
870 				RSA_private_decrypt(vallen,
871 				    (u_char *)ep->pkt,
872 				    (u_char *)&temp32,
873 				    host_pkey->pkey.rsa,
874 				    RSA_PKCS1_OAEP_PADDING);
875 				cookie = ntohl(temp32);
876 			} else {
877 				rval = XEVNT_CKY;
878 				break;
879 			}
880 
881 			/*
882 			 * Install cookie values and light the cookie
883 			 * bit. If this is not broadcast client mode, we
884 			 * are done here.
885 			 */
886 			key_expire(peer);
887 			peer->cookval.tstamp = ep->tstamp;
888 			peer->cookval.fstamp = ep->fstamp;
889 			if (peer->crypto & CRYPTO_FLAG_AGREE)
890 				peer->pcookie ^= cookie;
891 			else
892 				peer->pcookie = cookie;
893 			if (peer->hmode == MODE_CLIENT &&
894 			    !(peer->cast_flags & MDF_BCLNT))
895 				peer->crypto |= CRYPTO_FLAG_AUTO;
896 			else
897 				peer->crypto &= ~CRYPTO_FLAG_AUTO;
898 			peer->crypto |= CRYPTO_FLAG_AGREE;
899 			peer->flash &= ~TEST10;
900 			sprintf(statstr, "cook %x ts %u fs %u",
901 			    peer->pcookie, ntohl(ep->tstamp),
902 			    ntohl(ep->fstamp));
903 			record_crypto_stats(&peer->srcadr, statstr);
904 #ifdef DEBUG
905 			if (debug)
906 				printf("crypto_recv: %s\n", statstr);
907 #endif
908 			break;
909 
910 		/*
911 		 * Install autokey values in broadcast client and
912 		 * symmetric modes. We have to do this every time the
913 		 * sever/peer cookie changes or a new keylist is
914 		 * rolled. Ordinarily, this is automatic as this message
915 		 * is piggybacked on the first NTP packet sent upon
916 		 * either of these events. Note that a broadcast client
917 		 * or symmetric peer can receive this response without a
918 		 * matching request.
919 		 */
920 		case CRYPTO_AUTO | CRYPTO_RESP:
921 
922 			/*
923 			 * Discard the message if invalid or identity
924 			 * not confirmed or signature not verified with
925 			 * respect to the receive autokey values.
926 			 */
927 			if (!(peer->crypto & CRYPTO_FLAG_VRFY))
928 				break;
929 
930 			if ((rval = crypto_verify(ep, &peer->recval,
931 			    peer)) != XEVNT_OK)
932 				break;
933 
934 			/*
935 			 * Install autokey values and light the
936 			 * autokey bit. This is not hard.
937 			 */
938 			if (peer->recval.ptr == NULL)
939 				peer->recval.ptr =
940 				    emalloc(sizeof(struct autokey));
941 			bp = (struct autokey *)peer->recval.ptr;
942 			peer->recval.tstamp = ep->tstamp;
943 			peer->recval.fstamp = ep->fstamp;
944 			ap = (struct autokey *)ep->pkt;
945 			bp->seq = ntohl(ap->seq);
946 			bp->key = ntohl(ap->key);
947 			peer->pkeyid = bp->key;
948 			peer->crypto |= CRYPTO_FLAG_AUTO;
949 			peer->flash &= ~TEST10;
950 			sprintf(statstr,
951 			    "auto seq %d key %x ts %u fs %u", bp->seq,
952 			    bp->key, ntohl(ep->tstamp),
953 			    ntohl(ep->fstamp));
954 			record_crypto_stats(&peer->srcadr, statstr);
955 #ifdef DEBUG
956 			if (debug)
957 				printf("crypto_recv: %s\n", statstr);
958 #endif
959 			break;
960 
961 		/*
962 		 * Install leapseconds table in symmetric modes. This
963 		 * table is proventicated to the NIST primary servers,
964 		 * either by copying the file containing the table from
965 		 * a NIST server to a trusted server or directly using
966 		 * this protocol. While the entire table is installed at
967 		 * the server, presently only the current TAI offset is
968 		 * provided via the kernel to other applications.
969 		 */
970 		case CRYPTO_TAI:
971 
972 			/*
973 			 * Discard the message if invalid or identity
974 			 * not confirmed.
975 			 */
976 			if (!(peer->crypto & CRYPTO_FLAG_VRFY))
977 				break;
978 
979 			if ((rval = crypto_verify(ep, NULL, peer)) !=
980 			    XEVNT_OK)
981 				break;
982 
983 			/*
984 			 * Pass the extension field to the transmit
985 			 * side. Continue below if a leapseconds table
986 			 * accompanies the message.
987 			 */
988 			fp = emalloc(len);
989 			memcpy(fp, ep, len);
990 			temp32 = CRYPTO_RESP;
991 			fp->opcode |= htonl(temp32);
992 			peer->cmmd = fp;
993 			if (len <= VALUE_LEN) {
994 				peer->flash &= ~TEST10;
995 				break;
996 			}
997 			/* fall through */
998 
999 		case CRYPTO_TAI | CRYPTO_RESP:
1000 
1001 			/*
1002 			 * Discard the message if invalid or identity
1003 			 * not confirmed or signature not verified with
1004 			 * respect to the leapsecond table values.
1005 			 */
1006 			if (!(peer->crypto & CRYPTO_FLAG_VRFY))
1007 				break;
1008 
1009 			if ((rval = crypto_verify(ep, &peer->tai_leap,
1010 			    peer)) != XEVNT_OK)
1011 				break;
1012 
1013 			/*
1014 			 * Initialize peer variables, leapseconds
1015 			 * structure and extension field in network byte
1016 			 * order. Since a filestamp may have changed,
1017 			 * recompute the signatures.
1018 			 */
1019 			peer->tai_leap.tstamp = ep->tstamp;
1020 			peer->tai_leap.fstamp = ep->fstamp;
1021 			peer->tai_leap.vallen = ep->vallen;
1022 
1023 			/*
1024 			 * Install the new table if there is no stored
1025 			 * table or the new table is more recent than
1026 			 * the stored table. Since a filestamp may have
1027 			 * changed, recompute the signatures.
1028 			 */
1029 			if (ntohl(peer->tai_leap.fstamp) >
1030 			    ntohl(tai_leap.fstamp)) {
1031 				tai_leap.fstamp = ep->fstamp;
1032 				tai_leap.vallen = ep->vallen;
1033 				if (tai_leap.ptr != NULL)
1034 					free(tai_leap.ptr);
1035 				tai_leap.ptr = emalloc(vallen);
1036 				memcpy(tai_leap.ptr, ep->pkt, vallen);
1037 				crypto_update();
1038 				sys_tai = vallen / 4 + TAI_1972 - 1;
1039 			}
1040 			crypto_flags |= CRYPTO_FLAG_TAI;
1041 			peer->crypto |= CRYPTO_FLAG_LEAP;
1042 			peer->flash &= ~TEST10;
1043 #ifdef KERNEL_PLL
1044 #if NTP_API > 3
1045 			/*
1046 			 * If the kernel cooperates, initialize the
1047 			 * current TAI offset.
1048 			 */
1049 			ntv.modes = MOD_TAI;
1050 			ntv.constant = sys_tai;
1051 			(void)ntp_adjtime(&ntv);
1052 #endif /* NTP_API */
1053 #endif /* KERNEL_PLL */
1054 			sprintf(statstr, "leap %u ts %u fs %u",
1055 			    vallen, ntohl(ep->tstamp),
1056 			    ntohl(ep->fstamp));
1057 			record_crypto_stats(&peer->srcadr, statstr);
1058 #ifdef DEBUG
1059 			if (debug)
1060 				printf("crypto_recv: %s\n", statstr);
1061 #endif
1062 			break;
1063 
1064 		/*
1065 		 * We come here in symmetric modes for miscellaneous
1066 		 * commands that have value fields but are processed on
1067 		 * the transmit side. All we need do here is check for
1068 		 * valid field length. Remaining checks are below and on
1069 		 * the transmit side.
1070 		 */
1071 		case CRYPTO_IFF:
1072 		case CRYPTO_GQ:
1073 		case CRYPTO_MV:
1074 		case CRYPTO_SIGN:
1075 			if (len < VALUE_LEN) {
1076 				rval = XEVNT_LEN;
1077 				break;
1078 			}
1079 
1080 			/* fall through */
1081 
1082 		/*
1083 		 * We come here for miscellaneous requests and unknown
1084 		 * requests and responses. If an unknown response or
1085 		 * error, forget it. If a request, save the extension
1086 		 * field for later. Unknown requests will be caught on
1087 		 * the transmit side.
1088 		 */
1089 		default:
1090 			if (code & (CRYPTO_RESP | CRYPTO_ERROR)) {
1091 				rval = XEVNT_LEN;
1092 			} else if ((rval = crypto_verify(ep, NULL,
1093 			    peer)) == XEVNT_OK) {
1094 				fp = emalloc(len);
1095 				memcpy(fp, ep, len);
1096 				temp32 = CRYPTO_RESP;
1097 				fp->opcode |= htonl(temp32);
1098 				peer->cmmd = fp;
1099 			}
1100 		}
1101 
1102 		/*
1103 		 * We log everything except length/format errors and
1104 		 * duplicates, which are log clogging vulnerabilities.
1105 		 * The first error found terminates the extension field
1106 		 * scan and we return the laundry to the caller.
1107 		 */
1108 		if (rval != XEVNT_OK) {
1109 			sprintf(statstr,
1110 			    "error %x opcode %x ts %u fs %u", rval,
1111 			    code, tstamp, fstamp);
1112 			if (rval > XEVNT_TSP)
1113 				record_crypto_stats(&peer->srcadr,
1114 				    statstr);
1115 			report_event(rval, peer);
1116 #ifdef DEBUG
1117 			if (debug)
1118 				printf("crypto_recv: %s\n", statstr);
1119 #endif
1120 			break;
1121 		}
1122 		authlen += len;
1123 	}
1124 	return (rval);
1125 }
1126 
1127 
1128 /*
1129  * crypto_xmit - construct extension fields
1130  *
1131  * This routine is called both when an association is configured and
1132  * when one is not. The only case where this matters is to retrieve the
1133  * autokey information, in which case the caller has to provide the
1134  * association ID to match the association.
1135  *
1136  * Returns length of extension field.
1137  */
1138 int
1139 crypto_xmit(
1140 	struct pkt *xpkt,	/* transmit packet pointer */
1141 	struct sockaddr_storage *srcadr_sin,	/* active runway */
1142 	int	start,		/* offset to extension field */
1143 	struct exten *ep,	/* extension pointer */
1144 	keyid_t cookie		/* session cookie */
1145 	)
1146 {
1147 	u_int32	*pkt;		/* packet pointer */
1148 	struct peer *peer;	/* peer structure pointer */
1149 	u_int	opcode;		/* extension field opcode */
1150 	struct exten *fp;	/* extension pointers */
1151 	struct cert_info *cp;	/* certificate info/value pointer */
1152 	char	certname[MAXHOSTNAME + 1]; /* subject name buffer */
1153 	char	statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1154 	u_int	vallen;
1155 	u_int	len;
1156 	struct value vtemp;
1157 	associd_t associd;
1158 	int	rval;
1159 	keyid_t tcookie;
1160 
1161 	/*
1162 	 * Generate the requested extension field request code, length
1163 	 * and association ID. If this is a response and the host is not
1164 	 * synchronized, light the error bit and go home.
1165 	 */
1166 	pkt = (u_int32 *)xpkt + start / 4;
1167 	fp = (struct exten *)pkt;
1168 	opcode = ntohl(ep->opcode);
1169 	associd = (associd_t) ntohl(ep->associd);
1170 	fp->associd = htonl(associd);
1171 	len = 8;
1172 	rval = XEVNT_OK;
1173 	switch (opcode & 0xffff0000) {
1174 
1175 	/*
1176 	 * Send association request and response with status word and
1177 	 * host name. Note, this message is not signed and the filestamp
1178 	 * contains only the status word. We check at this point whether
1179 	 * the identity schemes are compatible to save tears later on.
1180 	 */
1181 	case CRYPTO_ASSOC | CRYPTO_RESP:
1182 	case CRYPTO_ASSOC:
1183 		len += crypto_send(fp, &hostval);
1184 		if (crypto_time() == 0)
1185 			fp->fstamp = 0;
1186 		else
1187 			fp->fstamp = htonl(crypto_flags);
1188 		break;
1189 
1190 	/*
1191 	 * Send certificate request. Use the values from the extension
1192 	 * field.
1193 	 */
1194 	case CRYPTO_CERT:
1195 		memset(&vtemp, 0, sizeof(vtemp));
1196 		vtemp.tstamp = ep->tstamp;
1197 		vtemp.fstamp = ep->fstamp;
1198 		vtemp.vallen = ep->vallen;
1199 		vtemp.ptr = (unsigned char *)ep->pkt;
1200 		len += crypto_send(fp, &vtemp);
1201 		break;
1202 
1203 	/*
1204 	 * Send certificate response or sign request. Use the values
1205 	 * from the certificate. If the request contains no subject
1206 	 * name, assume the name of this host. This is for backwards
1207 	 * compatibility.  Light the error bit if no certificate with
1208 	 * the given subject name is found. Of course, private
1209 	 * certificates are never sent.
1210 	 */
1211 	case CRYPTO_SIGN:
1212 	case CRYPTO_CERT | CRYPTO_RESP:
1213 		vallen = ntohl(ep->vallen);
1214 		if (vallen == 8) {
1215 			strcpy(certname, sys_hostname);
1216 		} else if (vallen == 0 || vallen > MAXHOSTNAME) {
1217 			opcode |= CRYPTO_ERROR;
1218 			break;
1219 
1220 		} else {
1221 			memcpy(certname, ep->pkt, vallen);
1222 			certname[vallen] = '\0';
1223 		}
1224 		for (cp = cinfo; cp != NULL; cp = cp->link) {
1225 			if (cp->flags & CERT_PRIV)
1226 				continue;
1227 			if (strcmp(certname, cp->subject) == 0) {
1228 				len += crypto_send(fp, &cp->cert);
1229 				break;
1230 			}
1231 		}
1232 		if (cp == NULL)
1233 			opcode |= CRYPTO_ERROR;
1234 		break;
1235 
1236 	/*
1237 	 * Send challenge in Schnorr (IFF) identity scheme.
1238 	 */
1239 	case CRYPTO_IFF:
1240 		if ((peer = findpeerbyassoc(ep->pkt[0])) == NULL) {
1241 			opcode |= CRYPTO_ERROR;
1242 			break;
1243 		}
1244 		if ((rval = crypto_alice(peer, &vtemp)) == XEVNT_OK)
1245 			len += crypto_send(fp, &vtemp);
1246 		value_free(&vtemp);
1247 		break;
1248 
1249 	/*
1250 	 * Send response in Schnorr (IFF) identity scheme.
1251 	 */
1252 	case CRYPTO_IFF | CRYPTO_RESP:
1253 		if ((rval = crypto_bob(ep, &vtemp)) == XEVNT_OK)
1254 			len += crypto_send(fp, &vtemp);
1255 		value_free(&vtemp);
1256 		break;
1257 
1258 	/*
1259 	 * Send challenge in Guillou-Quisquater (GQ) identity scheme.
1260 	 */
1261 	case CRYPTO_GQ:
1262 		if ((peer = findpeerbyassoc(ep->pkt[0])) == NULL) {
1263 			opcode |= CRYPTO_ERROR;
1264 			break;
1265 		}
1266 		if ((rval = crypto_alice2(peer, &vtemp)) == XEVNT_OK)
1267 			len += crypto_send(fp, &vtemp);
1268 		value_free(&vtemp);
1269 		break;
1270 
1271 	/*
1272 	 * Send response in Guillou-Quisquater (GQ) identity scheme.
1273 	 */
1274 	case CRYPTO_GQ | CRYPTO_RESP:
1275 		if ((rval = crypto_bob2(ep, &vtemp)) == XEVNT_OK)
1276 			len += crypto_send(fp, &vtemp);
1277 		value_free(&vtemp);
1278 		break;
1279 
1280 	/*
1281 	 * Send challenge in MV identity scheme.
1282 	 */
1283 	case CRYPTO_MV:
1284 		if ((peer = findpeerbyassoc(ep->pkt[0])) == NULL) {
1285 			opcode |= CRYPTO_ERROR;
1286 			break;
1287 		}
1288 		if ((rval = crypto_alice3(peer, &vtemp)) == XEVNT_OK)
1289 			len += crypto_send(fp, &vtemp);
1290 		value_free(&vtemp);
1291 		break;
1292 
1293 	/*
1294 	 * Send response in MV identity scheme.
1295 	 */
1296 	case CRYPTO_MV | CRYPTO_RESP:
1297 		if ((rval = crypto_bob3(ep, &vtemp)) == XEVNT_OK)
1298 			len += crypto_send(fp, &vtemp);
1299 		value_free(&vtemp);
1300 		break;
1301 
1302 	/*
1303 	 * Send certificate sign response. The integrity of the request
1304 	 * certificate has already been verified on the receive side.
1305 	 * Sign the response using the local server key. Use the
1306 	 * filestamp from the request and use the timestamp as the
1307 	 * current time. Light the error bit if the certificate is
1308 	 * invalid or contains an unverified signature.
1309 	 */
1310 	case CRYPTO_SIGN | CRYPTO_RESP:
1311 		if ((rval = cert_sign(ep, &vtemp)) == XEVNT_OK)
1312 			len += crypto_send(fp, &vtemp);
1313 		value_free(&vtemp);
1314 		break;
1315 
1316 	/*
1317 	 * Send public key and signature. Use the values from the public
1318 	 * key.
1319 	 */
1320 	case CRYPTO_COOK:
1321 		len += crypto_send(fp, &pubkey);
1322 		break;
1323 
1324 	/*
1325 	 * Encrypt and send cookie and signature. Light the error bit if
1326 	 * anything goes wrong.
1327 	 */
1328 	case CRYPTO_COOK | CRYPTO_RESP:
1329 		if ((opcode & 0xffff) < VALUE_LEN) {
1330 			opcode |= CRYPTO_ERROR;
1331 			break;
1332 		}
1333 		if (PKT_MODE(xpkt->li_vn_mode) == MODE_SERVER) {
1334 			tcookie = cookie;
1335 		} else {
1336 			if ((peer = findpeerbyassoc(associd)) == NULL) {
1337 				opcode |= CRYPTO_ERROR;
1338 				break;
1339 			}
1340 			tcookie = peer->pcookie;
1341 		}
1342 		if ((rval = crypto_encrypt(ep, &vtemp, &tcookie)) ==
1343 		    XEVNT_OK)
1344 			len += crypto_send(fp, &vtemp);
1345 		value_free(&vtemp);
1346 		break;
1347 
1348 	/*
1349 	 * Find peer and send autokey data and signature in broadcast
1350 	 * server and symmetric modes. Use the values in the autokey
1351 	 * structure. If no association is found, either the server has
1352 	 * restarted with new associations or some perp has replayed an
1353 	 * old message, in which case light the error bit.
1354 	 */
1355 	case CRYPTO_AUTO | CRYPTO_RESP:
1356 		if ((peer = findpeerbyassoc(associd)) == NULL) {
1357 			opcode |= CRYPTO_ERROR;
1358 			break;
1359 		}
1360 		peer->flags &= ~FLAG_ASSOC;
1361 		len += crypto_send(fp, &peer->sndval);
1362 		break;
1363 
1364 	/*
1365 	 * Send leapseconds table and signature. Use the values from the
1366 	 * tai structure. If no table has been loaded, just send a
1367 	 * request.
1368 	 */
1369 	case CRYPTO_TAI:
1370 	case CRYPTO_TAI | CRYPTO_RESP:
1371 		if (crypto_flags & CRYPTO_FLAG_TAI)
1372 			len += crypto_send(fp, &tai_leap);
1373 		break;
1374 
1375 	/*
1376 	 * Default - Fall through for requests; for unknown responses,
1377 	 * flag as error.
1378 	 */
1379 	default:
1380 		if (opcode & CRYPTO_RESP)
1381 			opcode |= CRYPTO_ERROR;
1382 	}
1383 
1384 	/*
1385 	 * We ignore length/format errors and duplicates. Other errors
1386 	 * are reported to the log and deny further service. To really
1387 	 * persistent rascals we toss back a kiss-of-death grenade.
1388 	 */
1389 	if (rval > XEVNT_TSP) {
1390 		opcode |= CRYPTO_ERROR;
1391 		sprintf(statstr, "error %x opcode %x", rval, opcode);
1392 		record_crypto_stats(srcadr_sin, statstr);
1393 #ifdef DEBUG
1394 		if (debug)
1395 			printf("crypto_xmit: %s\n", statstr);
1396 #endif
1397 	}
1398 
1399 	/*
1400 	 * Round up the field length to a multiple of 8 bytes and save
1401 	 * the request code and length.
1402 	 */
1403 	len = ((len + 7) / 8) * 8;
1404 	fp->opcode = htonl((opcode & 0xffff0000) | len);
1405 #ifdef DEBUG
1406 	if (debug)
1407 		printf(
1408 		    "crypto_xmit: ext offset %d len %u code %x assocID %d\n",
1409 		    start, len, opcode>> 16, associd);
1410 #endif
1411 	return (len);
1412 }
1413 
1414 
1415 /*
1416  * crypto_verify - parse and verify the extension field and value
1417  *
1418  * Returns
1419  * XEVNT_OK	success
1420  * XEVNT_LEN	bad field format or length
1421  * XEVNT_TSP	bad timestamp
1422  * XEVNT_FSP	bad filestamp
1423  * XEVNT_PUB	bad or missing public key
1424  * XEVNT_SGL	bad signature length
1425  * XEVNT_SIG	signature not verified
1426  */
1427 static int
1428 crypto_verify(
1429 	struct exten *ep,	/* extension pointer */
1430 	struct value *vp,	/* value pointer */
1431 	struct peer *peer	/* peer structure pointer */
1432 	)
1433 {
1434 	EVP_PKEY *pkey;		/* server public key */
1435 	EVP_MD_CTX ctx;		/* signature context */
1436 	tstamp_t tstamp;	/* timestamp */
1437 	tstamp_t fstamp;	/* filestamp */
1438 	u_int	vallen;		/* value length */
1439 	u_int	siglen;		/* signature length */
1440 	u_int	opcode, len;
1441 	int	rval;
1442 	int	i;
1443 
1444 	/*
1445 	 * We require valid opcode and field length, timestamp,
1446 	 * filestamp, public key, digest, signature length and
1447 	 * signature, where relevant. Note that preliminary length
1448 	 * checks are done in the main loop.
1449 	 */
1450 	len = ntohl(ep->opcode) & 0x0000ffff;
1451 	opcode = ntohl(ep->opcode) & 0xffff0000;
1452 
1453 	/*
1454 	 * Check for valid operation code and protocol. The opcode must
1455 	 * not have the error bit set. If a response, it must have a
1456 	 * value header. If a request and does not contain a value
1457 	 * header, no need for further checking.
1458 	 */
1459 	if (opcode & CRYPTO_ERROR)
1460 		return (XEVNT_LEN);
1461  	if (opcode & CRYPTO_RESP) {
1462  		if (len < VALUE_LEN)
1463 			return (XEVNT_LEN);
1464 	} else {
1465  		if (len < VALUE_LEN)
1466 			return (XEVNT_OK);
1467 	}
1468 	/*
1469 	 * We have a value header. Check for valid field lengths. The
1470 	 * field length must be long enough to contain the value header,
1471 	 * value and signature. If a request and a previous request of
1472 	 * the same type is pending, discard the previous request. If a
1473 	 * request but no signature, there is no need for further
1474 	 * checking.
1475 	 */
1476 	vallen = ntohl(ep->vallen);
1477 	if (len < ((VALUE_LEN + vallen + 3) / 4) * 4)
1478 		return (XEVNT_LEN);
1479 
1480 	i = (vallen + 3) / 4;
1481 	siglen = ntohl(ep->pkt[i++]);
1482 	if (len < VALUE_LEN + vallen + siglen)
1483 		return (XEVNT_LEN);
1484 
1485 	if (!(opcode & CRYPTO_RESP)) {
1486 		if (peer->cmmd != NULL) {
1487 			if ((opcode | CRYPTO_RESP) ==
1488 			    (ntohl(peer->cmmd->opcode) & 0xffff0000)) {
1489 				free(peer->cmmd);
1490 				peer->cmmd = NULL;
1491 			} else {
1492 				return (XEVNT_LEN);
1493 			}
1494 		}
1495 		if (siglen == 0)
1496 			return (XEVNT_OK);
1497 	}
1498 
1499 	/*
1500 	 * We have a signature. Check for valid timestamp and filestamp.
1501 	 * The timestamp must not precede the filestamp. The timestamp
1502 	 * and filestamp must not precede the corresponding values in
1503 	 * the value structure. Once the autokey values have been
1504 	 * installed, the timestamp must always be later than the
1505 	 * corresponding value in the value structure. Duplicate
1506 	 * timestamps are illegal once the cookie has been validated.
1507 	 */
1508 	rval = XEVNT_OK;
1509 	if (crypto_flags & peer->crypto & CRYPTO_FLAG_PRIV)
1510 		pkey = sign_pkey;
1511 	else
1512 		pkey = peer->pkey;
1513 	tstamp = ntohl(ep->tstamp);
1514 	fstamp = ntohl(ep->fstamp);
1515 	if (tstamp == 0 || tstamp < fstamp) {
1516 		rval = XEVNT_TSP;
1517 	} else if (vp != NULL && (tstamp < ntohl(vp->tstamp) ||
1518 	    (tstamp == ntohl(vp->tstamp) && (peer->crypto &
1519 	    CRYPTO_FLAG_AUTO)))) {
1520 		rval = XEVNT_TSP;
1521 	} else if (vp != NULL && (tstamp < ntohl(vp->fstamp) || fstamp <
1522 	    ntohl(vp->fstamp))) {
1523 		rval = XEVNT_FSP;
1524 
1525 	/*
1526 	 * If a public key and digest is present, and if valid key
1527 	 * length, check for valid signature. Note that the first valid
1528 	 * signature lights the proventic bit.
1529 	 */
1530 	} else if (pkey == NULL || peer->digest == NULL) {
1531 		/* fall through */
1532 	} else if (siglen != (u_int) EVP_PKEY_size(pkey)) {
1533 		rval = XEVNT_SGL;
1534 	} else {
1535 		EVP_VerifyInit(&ctx, peer->digest);
1536 		EVP_VerifyUpdate(&ctx, (u_char *)&ep->tstamp, vallen +
1537 		    12);
1538 		if (EVP_VerifyFinal(&ctx, (u_char *)&ep->pkt[i], siglen,
1539 		    pkey)) {
1540 			if (peer->crypto & CRYPTO_FLAG_VRFY)
1541 				peer->crypto |= CRYPTO_FLAG_PROV;
1542 		} else {
1543 			rval = XEVNT_SIG;
1544 		}
1545 	}
1546 #ifdef DEBUG
1547 	if (debug > 1)
1548 		printf(
1549 		    "crypto_recv: verify %x vallen %u siglen %u ts %u fs %u\n",
1550 		    rval, vallen, siglen, tstamp, fstamp);
1551 #endif
1552 	return (rval);
1553 }
1554 
1555 
1556 /*
1557  * crypto_encrypt - construct encrypted cookie and signature from
1558  * extension field and cookie
1559  *
1560  * Returns
1561  * XEVNT_OK	success
1562  * XEVNT_PUB	bad or missing public key
1563  * XEVNT_CKY	bad or missing cookie
1564  */
1565 static int
1566 crypto_encrypt(
1567 	struct exten *ep,	/* extension pointer */
1568 	struct value *vp,	/* value pointer */
1569 	keyid_t	*cookie		/* server cookie */
1570 	)
1571 {
1572 	EVP_PKEY *pkey;		/* public key */
1573 	EVP_MD_CTX ctx;		/* signature context */
1574 	tstamp_t tstamp;	/* NTP timestamp */
1575 	u_int32	temp32;
1576 	u_int	len;
1577 	u_char	*ptr;
1578 
1579 	/*
1580 	 * Extract the public key from the request.
1581 	 */
1582 	len = ntohl(ep->vallen);
1583 	ptr = (u_char *)ep->pkt;
1584 	pkey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &ptr, len);
1585 	if (pkey == NULL) {
1586 		msyslog(LOG_ERR, "crypto_encrypt %s\n",
1587 		    ERR_error_string(ERR_get_error(), NULL));
1588 		return (XEVNT_PUB);
1589 	}
1590 
1591 	/*
1592 	 * Encrypt the cookie, encode in ASN.1 and sign.
1593 	 */
1594 	tstamp = crypto_time();
1595 	memset(vp, 0, sizeof(struct value));
1596 	vp->tstamp = htonl(tstamp);
1597 	vp->fstamp = hostval.tstamp;
1598 	len = EVP_PKEY_size(pkey);
1599 	vp->vallen = htonl(len);
1600 	vp->ptr = emalloc(len);
1601 	temp32 = htonl(*cookie);
1602 	if (!RSA_public_encrypt(4, (u_char *)&temp32, vp->ptr,
1603 	    pkey->pkey.rsa, RSA_PKCS1_OAEP_PADDING)) {
1604 		msyslog(LOG_ERR, "crypto_encrypt %s\n",
1605 		    ERR_error_string(ERR_get_error(), NULL));
1606 		EVP_PKEY_free(pkey);
1607 		return (XEVNT_CKY);
1608 	}
1609 	EVP_PKEY_free(pkey);
1610 	vp->siglen = 0;
1611 	if (tstamp == 0)
1612 		return (XEVNT_OK);
1613 	vp->sig = emalloc(sign_siglen);
1614 	EVP_SignInit(&ctx, sign_digest);
1615 	EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
1616 	EVP_SignUpdate(&ctx, vp->ptr, len);
1617 	if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
1618 		vp->siglen = htonl(len);
1619 	return (XEVNT_OK);
1620 }
1621 
1622 
1623 /*
1624  * crypto_ident - construct extension field for identity scheme
1625  *
1626  * This routine determines which identity scheme is in use and
1627  * constructs an extension field for that scheme.
1628  */
1629 u_int
1630 crypto_ident(
1631 	struct peer *peer	/* peer structure pointer */
1632 	)
1633 {
1634 	char	filename[MAXFILENAME + 1];
1635 
1636 	/*
1637 	 * If the server identity has already been verified, no further
1638 	 * action is necessary. Otherwise, try to load the identity file
1639 	 * of the certificate issuer. If the issuer file is not found,
1640 	 * try the host file. If nothing found, declare a cryptobust.
1641 	 * Note we can't get here unless the trusted certificate has
1642 	 * been found and the CRYPTO_FLAG_VALID bit is set, so the
1643 	 * certificate issuer is valid.
1644 	 */
1645 	if (peer->crypto & CRYPTO_FLAG_VRFY)
1646 		return (0);
1647 
1648 	if (peer->ident_pkey != NULL)
1649 		EVP_PKEY_free(peer->ident_pkey);
1650 	if (peer->crypto & CRYPTO_FLAG_GQ) {
1651 		snprintf(filename, MAXFILENAME, "ntpkey_gq_%s",
1652 		    peer->issuer);
1653 		peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1654 		if (peer->ident_pkey != NULL)
1655 			return (CRYPTO_GQ);
1656 
1657 		snprintf(filename, MAXFILENAME, "ntpkey_gq_%s",
1658 		    sys_hostname);
1659 		peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1660 		if (peer->ident_pkey != NULL)
1661 			return (CRYPTO_GQ);
1662 	}
1663 	if (peer->crypto & CRYPTO_FLAG_IFF) {
1664 		snprintf(filename, MAXFILENAME, "ntpkey_iff_%s",
1665 		    peer->issuer);
1666 		peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1667 		if (peer->ident_pkey != NULL)
1668 			return (CRYPTO_IFF);
1669 
1670 		snprintf(filename, MAXFILENAME, "ntpkey_iff_%s",
1671 		    sys_hostname);
1672 		peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1673 		if (peer->ident_pkey != NULL)
1674 			return (CRYPTO_IFF);
1675 	}
1676 	if (peer->crypto & CRYPTO_FLAG_MV) {
1677 		snprintf(filename, MAXFILENAME, "ntpkey_mv_%s",
1678 		    peer->issuer);
1679 		peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1680 		if (peer->ident_pkey != NULL)
1681 			return (CRYPTO_MV);
1682 
1683 		snprintf(filename, MAXFILENAME, "ntpkey_mv_%s",
1684 		    sys_hostname);
1685 		peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1686 		if (peer->ident_pkey != NULL)
1687 			return (CRYPTO_MV);
1688 	}
1689 
1690 	/*
1691 	 * No compatible identity scheme is available. Use the default
1692 	 * TC scheme.
1693 	 */
1694 	msyslog(LOG_INFO,
1695 	    "crypto_ident: no compatible identity scheme found");
1696 	return (0);
1697 }
1698 
1699 
1700 /*
1701  * crypto_args - construct extension field from arguments
1702  *
1703  * This routine creates an extension field with current timestamps and
1704  * specified opcode, association ID and optional string. Note that the
1705  * extension field is created here, but freed after the crypto_xmit()
1706  * call in the protocol module.
1707  *
1708  * Returns extension field pointer (no errors).
1709  */
1710 struct exten *
1711 crypto_args(
1712 	struct peer *peer,	/* peer structure pointer */
1713 	u_int	opcode,		/* operation code */
1714 	char	*str		/* argument string */
1715 	)
1716 {
1717 	tstamp_t tstamp;	/* NTP timestamp */
1718 	struct exten *ep;	/* extension field pointer */
1719 	u_int	len;		/* extension field length */
1720 
1721 	tstamp = crypto_time();
1722 	len = sizeof(struct exten);
1723 	if (str != NULL)
1724 		len += strlen(str);
1725 	ep = emalloc(len);
1726 	memset(ep, 0, len);
1727 	ep->opcode = htonl(opcode + len);
1728 
1729 	/*
1730 	 * If a response, send our ID; if a request, send the
1731 	 * responder's ID.
1732 	 */
1733 	if (opcode & CRYPTO_RESP)
1734 		ep->associd = htonl(peer->associd);
1735 	else
1736 		ep->associd = htonl(peer->assoc);
1737 	ep->tstamp = htonl(tstamp);
1738 	ep->fstamp = hostval.tstamp;
1739 	ep->vallen = 0;
1740 	if (str != NULL) {
1741 		ep->vallen = htonl(strlen(str));
1742 		memcpy((char *)ep->pkt, str, strlen(str));
1743 	} else {
1744 		ep->pkt[0] = peer->associd;
1745 	}
1746 	return (ep);
1747 }
1748 
1749 
1750 /*
1751  * crypto_send - construct extension field from value components
1752  *
1753  * Returns extension field length. Note: it is not polite to send a
1754  * nonempty signature with zero timestamp or a nonzero timestamp with
1755  * empty signature, but these rules are not enforced here.
1756  */
1757 u_int
1758 crypto_send(
1759 	struct exten *ep,	/* extension field pointer */
1760 	struct value *vp	/* value pointer */
1761 	)
1762 {
1763 	u_int	len, temp32;
1764 	int	i;
1765 
1766 	/*
1767 	 * Copy data. If the data field is empty or zero length, encode
1768 	 * an empty value with length zero.
1769 	 */
1770 	ep->tstamp = vp->tstamp;
1771 	ep->fstamp = vp->fstamp;
1772 	ep->vallen = vp->vallen;
1773 	len = 12;
1774 	temp32 = ntohl(vp->vallen);
1775 	if (temp32 > 0 && vp->ptr != NULL)
1776 		memcpy(ep->pkt, vp->ptr, temp32);
1777 
1778 	/*
1779 	 * Copy signature. If the signature field is empty or zero
1780 	 * length, encode an empty signature with length zero.
1781 	 */
1782 	i = (temp32 + 3) / 4;
1783 	len += i * 4 + 4;
1784 	ep->pkt[i++] = vp->siglen;
1785 	temp32 = ntohl(vp->siglen);
1786 	if (temp32 > 0 && vp->sig != NULL)
1787 		memcpy(&ep->pkt[i], vp->sig, temp32);
1788 	len += temp32;
1789 	return (len);
1790 }
1791 
1792 
1793 /*
1794  * crypto_update - compute new public value and sign extension fields
1795  *
1796  * This routine runs periodically, like once a day, and when something
1797  * changes. It updates the timestamps on three value structures and one
1798  * value structure list, then signs all the structures:
1799  *
1800  * hostval	host name (not signed)
1801  * pubkey	public key
1802  * cinfo	certificate info/value list
1803  * tai_leap	leapseconds file
1804  *
1805  * Filestamps are proventicated data, so this routine is run only when
1806  * the host has been synchronized to a proventicated source. Thus, the
1807  * timestamp is proventicated, too, and can be used to deflect
1808  * clogging attacks and even cook breakfast.
1809  *
1810  * Returns void (no errors)
1811  */
1812 void
1813 crypto_update(void)
1814 {
1815 	EVP_MD_CTX ctx;		/* message digest context */
1816 	struct cert_info *cp, *cpn, **zp; /* certificate info/value */
1817 	char	statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1818 	tstamp_t tstamp;	/* NTP timestamp */
1819 	u_int	len;
1820 
1821 	if ((tstamp = crypto_time()) == 0)
1822 		return;
1823 	hostval.tstamp = htonl(tstamp);
1824 
1825 	/*
1826 	 * Sign public key and timestamps. The filestamp is derived from
1827 	 * the host key file extension from wherever the file was
1828 	 * generated.
1829 	 */
1830 	if (pubkey.vallen != 0) {
1831 		pubkey.tstamp = hostval.tstamp;
1832 		pubkey.siglen = 0;
1833 		if (pubkey.sig == NULL)
1834 			pubkey.sig = emalloc(sign_siglen);
1835 		EVP_SignInit(&ctx, sign_digest);
1836 		EVP_SignUpdate(&ctx, (u_char *)&pubkey, 12);
1837 		EVP_SignUpdate(&ctx, pubkey.ptr, ntohl(pubkey.vallen));
1838 		if (EVP_SignFinal(&ctx, pubkey.sig, &len, sign_pkey))
1839 			pubkey.siglen = htonl(len);
1840 	}
1841 
1842 	/*
1843 	 * Sign certificates and timestamps. The filestamp is derived
1844 	 * from the certificate file extension from wherever the file
1845 	 * was generated. At the same time expired certificates are
1846 	 * expunged.
1847 	 */
1848 	zp = &cinfo;
1849 	for (cp = cinfo; cp != NULL; cp = cpn) {
1850 		cpn = cp->link;
1851 		if (tstamp > cp->last) {
1852 			*zp = cpn;
1853 			cert_free(cp);
1854 		} else {
1855 			cp->cert.tstamp = hostval.tstamp;
1856 			cp->cert.siglen = 0;
1857 			if (cp->cert.sig == NULL)
1858 				cp->cert.sig = emalloc(sign_siglen);
1859 			EVP_SignInit(&ctx, sign_digest);
1860 			EVP_SignUpdate(&ctx, (u_char *)&cp->cert, 12);
1861 			EVP_SignUpdate(&ctx, cp->cert.ptr,
1862 			    ntohl(cp->cert.vallen));
1863 			if (EVP_SignFinal(&ctx, cp->cert.sig, &len,
1864 			    sign_pkey))
1865 				cp->cert.siglen = htonl(len);
1866 			zp = &cp->link;
1867 		}
1868 	}
1869 
1870 	/*
1871 	 * Sign leapseconds table and timestamps. The filestamp is
1872 	 * derived from the leapsecond file extension from wherever the
1873 	 * file was generated.
1874 	 */
1875 	if (tai_leap.vallen != 0) {
1876 		tai_leap.tstamp = hostval.tstamp;
1877 		tai_leap.siglen = 0;
1878 		if (tai_leap.sig == NULL)
1879 			tai_leap.sig = emalloc(sign_siglen);
1880 		EVP_SignInit(&ctx, sign_digest);
1881 		EVP_SignUpdate(&ctx, (u_char *)&tai_leap, 12);
1882 		EVP_SignUpdate(&ctx, tai_leap.ptr,
1883 		    ntohl(tai_leap.vallen));
1884 		if (EVP_SignFinal(&ctx, tai_leap.sig, &len, sign_pkey))
1885 			tai_leap.siglen = htonl(len);
1886 	}
1887 	sprintf(statstr, "update ts %u", ntohl(hostval.tstamp));
1888 	record_crypto_stats(NULL, statstr);
1889 #ifdef DEBUG
1890 	if (debug)
1891 		printf("crypto_update: %s\n", statstr);
1892 #endif
1893 }
1894 
1895 
1896 /*
1897  * value_free - free value structure components.
1898  *
1899  * Returns void (no errors)
1900  */
1901 void
1902 value_free(
1903 	struct value *vp	/* value structure */
1904 	)
1905 {
1906 	if (vp->ptr != NULL)
1907 		free(vp->ptr);
1908 	if (vp->sig != NULL)
1909 		free(vp->sig);
1910 	memset(vp, 0, sizeof(struct value));
1911 }
1912 
1913 
1914 /*
1915  * crypto_time - returns current NTP time in seconds.
1916  */
1917 tstamp_t
1918 crypto_time()
1919 {
1920 	l_fp	tstamp;		/* NTP time */	L_CLR(&tstamp);
1921 
1922 	L_CLR(&tstamp);
1923 	if (sys_leap != LEAP_NOTINSYNC)
1924 		get_systime(&tstamp);
1925 	return (tstamp.l_ui);
1926 }
1927 
1928 
1929 /*
1930  * asn2ntp - convert ASN1_TIME time structure to NTP time in seconds.
1931  */
1932 u_long
1933 asn2ntp	(
1934 	ASN1_TIME *asn1time	/* pointer to ASN1_TIME structure */
1935 	)
1936 {
1937 	char	*v;		/* pointer to ASN1_TIME string */
1938 	struct	tm tm;		/* used to convert to NTP time */
1939 
1940 	/*
1941 	 * Extract time string YYMMDDHHMMSSZ from ASN1 time structure.
1942 	 * Note that the YY, MM, DD fields start with one, the HH, MM,
1943 	 * SS fiels start with zero and the Z character should be 'Z'
1944 	 * for UTC. Also note that years less than 50 map to years
1945 	 * greater than 100. Dontcha love ASN.1? Better than MIL-188.
1946 	 */
1947 	if (asn1time->length > 13)
1948 		return ((u_long)(~0));	/* We can't use -1 here. It's invalid */
1949 	v = (char *)asn1time->data;
1950 	tm.tm_year = (v[0] - '0') * 10 + v[1] - '0';
1951 	if (tm.tm_year < 50)
1952 		tm.tm_year += 100;
1953 	tm.tm_mon = (v[2] - '0') * 10 + v[3] - '0' - 1;
1954 	tm.tm_mday = (v[4] - '0') * 10 + v[5] - '0';
1955 	tm.tm_hour = (v[6] - '0') * 10 + v[7] - '0';
1956 	tm.tm_min = (v[8] - '0') * 10 + v[9] - '0';
1957 	tm.tm_sec = (v[10] - '0') * 10 + v[11] - '0';
1958 	tm.tm_wday = 0;
1959 	tm.tm_yday = 0;
1960 	tm.tm_isdst = 0;
1961 	return (timegm(&tm) + JAN_1970);
1962 }
1963 
1964 
1965 /*
1966  * bigdig() - compute a BIGNUM MD5 hash of a BIGNUM number.
1967  */
1968 static int
1969 bighash(
1970 	BIGNUM	*bn,		/* BIGNUM * from */
1971 	BIGNUM	*bk		/* BIGNUM * to */
1972 	)
1973 {
1974 	EVP_MD_CTX ctx;		/* message digest context */
1975 	u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
1976 	u_char	*ptr;		/* a BIGNUM as binary string */
1977 	u_int	len;
1978 
1979 	len = BN_num_bytes(bn);
1980 	ptr = emalloc(len);
1981 	BN_bn2bin(bn, ptr);
1982 	EVP_DigestInit(&ctx, EVP_md5());
1983 	EVP_DigestUpdate(&ctx, ptr, len);
1984 	EVP_DigestFinal(&ctx, dgst, &len);
1985 	BN_bin2bn(dgst, len, bk);
1986 	return (1);
1987 }
1988 
1989 
1990 /*
1991  ***********************************************************************
1992  *								       *
1993  * The following routines implement the Schnorr (IFF) identity scheme  *
1994  *								       *
1995  ***********************************************************************
1996  *
1997  * The Schnorr (IFF) identity scheme is intended for use when
1998  * the ntp-genkeys program does not generate the certificates used in
1999  * the protocol and the group key cannot be conveyed in the certificate
2000  * itself. For this purpose, new generations of IFF values must be
2001  * securely transmitted to all members of the group before use. The
2002  * scheme is self contained and independent of new generations of host
2003  * keys, sign keys and certificates.
2004  *
2005  * The IFF identity scheme is based on DSA cryptography and algorithms
2006  * described in Stinson p. 285. The IFF values hide in a DSA cuckoo
2007  * structure, but only the primes and generator are used. The p is a
2008  * 512-bit prime, q a 160-bit prime that divides p - 1 and is a qth root
2009  * of 1 mod p; that is, g^q = 1 mod p. The TA rolls primvate random
2010  * group key b disguised as a DSA structure member, then computes public
2011  * key g^(q - b). These values are shared only among group members and
2012  * never revealed in messages. Alice challenges Bob to confirm identity
2013  * using the protocol described below.
2014  *
2015  * How it works
2016  *
2017  * The scheme goes like this. Both Alice and Bob have the public primes
2018  * p, q and generator g. The TA gives private key b to Bob and public
2019  * key v = g^(q - a) mod p to Alice.
2020  *
2021  * Alice rolls new random challenge r and sends to Bob in the IFF
2022  * request message. Bob rolls new random k, then computes y = k + b r
2023  * mod q and x = g^k mod p and sends (y, hash(x)) to Alice in the
2024  * response message. Besides making the response shorter, the hash makes
2025  * it effectivey impossible for an intruder to solve for b by observing
2026  * a number of these messages.
2027  *
2028  * Alice receives the response and computes g^y v^r mod p. After a bit
2029  * of algebra, this simplifies to g^k. If the hash of this result
2030  * matches hash(x), Alice knows that Bob has the group key b. The signed
2031  * response binds this knowledge to Bob's private key and the public key
2032  * previously received in his certificate.
2033  *
2034  * crypto_alice - construct Alice's challenge in IFF scheme
2035  *
2036  * Returns
2037  * XEVNT_OK	success
2038  * XEVNT_PUB	bad or missing public key
2039  * XEVNT_ID	bad or missing identity parameters
2040  */
2041 static int
2042 crypto_alice(
2043 	struct peer *peer,	/* peer pointer */
2044 	struct value *vp	/* value pointer */
2045 	)
2046 {
2047 	DSA	*dsa;		/* IFF parameters */
2048 	BN_CTX	*bctx;		/* BIGNUM context */
2049 	EVP_MD_CTX ctx;		/* signature context */
2050 	tstamp_t tstamp;
2051 	u_int	len;
2052 
2053 	/*
2054 	 * The identity parameters must have correct format and content.
2055 	 */
2056 	if (peer->ident_pkey == NULL)
2057 		return (XEVNT_ID);
2058 	if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
2059 		msyslog(LOG_INFO, "crypto_alice: defective key");
2060 		return (XEVNT_PUB);
2061 	}
2062 
2063 	/*
2064 	 * Roll new random r (0 < r < q). The OpenSSL library has a bug
2065 	 * omitting BN_rand_range, so we have to do it the hard way.
2066 	 */
2067 	bctx = BN_CTX_new();
2068 	len = BN_num_bytes(dsa->q);
2069 	if (peer->iffval != NULL)
2070 		BN_free(peer->iffval);
2071 	peer->iffval = BN_new();
2072 	BN_rand(peer->iffval, len * 8, -1, 1);	/* r */
2073 	BN_mod(peer->iffval, peer->iffval, dsa->q, bctx);
2074 	BN_CTX_free(bctx);
2075 
2076 	/*
2077 	 * Sign and send to Bob. The filestamp is from the local file.
2078 	 */
2079 	tstamp = crypto_time();
2080 	memset(vp, 0, sizeof(struct value));
2081 	vp->tstamp = htonl(tstamp);
2082 	vp->fstamp = htonl(peer->fstamp);
2083 	vp->vallen = htonl(len);
2084 	vp->ptr = emalloc(len);
2085 	BN_bn2bin(peer->iffval, vp->ptr);
2086 	vp->siglen = 0;
2087 	if (tstamp == 0)
2088 		return (XEVNT_OK);
2089 	vp->sig = emalloc(sign_siglen);
2090 	EVP_SignInit(&ctx, sign_digest);
2091 	EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2092 	EVP_SignUpdate(&ctx, vp->ptr, len);
2093 	if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2094 		vp->siglen = htonl(len);
2095 	return (XEVNT_OK);
2096 }
2097 
2098 
2099 /*
2100  * crypto_bob - construct Bob's response to Alice's challenge
2101  *
2102  * Returns
2103  * XEVNT_OK	success
2104  * XEVNT_PUB	bad or missing public key
2105  */
2106 static int
2107 crypto_bob(
2108 	struct exten *ep,	/* extension pointer */
2109 	struct value *vp	/* value pointer */
2110 	)
2111 {
2112 	DSA	*dsa;		/* IFF parameters */
2113 	DSA_SIG	*sdsa;		/* DSA signature context fake */
2114 	BN_CTX	*bctx;		/* BIGNUM context */
2115 	EVP_MD_CTX ctx;		/* signature context */
2116 	tstamp_t tstamp;	/* NTP timestamp */
2117 	BIGNUM	*bn, *bk, *r;
2118 	u_char	*ptr;
2119 	u_int	len;
2120 
2121 	/*
2122 	 * If the IFF parameters are not valid, something awful
2123 	 * happened or we are being tormented.
2124 	 */
2125 	if (!(crypto_flags & CRYPTO_FLAG_IFF)) {
2126 		msyslog(LOG_INFO, "crypto_bob: scheme unavailable");
2127 		return (XEVNT_PUB);
2128 	}
2129 	dsa = iffpar_pkey->pkey.dsa;
2130 
2131 	/*
2132 	 * Extract r from the challenge.
2133 	 */
2134 	len = ntohl(ep->vallen);
2135 	if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2136 		msyslog(LOG_ERR, "crypto_bob %s\n",
2137 		    ERR_error_string(ERR_get_error(), NULL));
2138 		return (XEVNT_PUB);
2139 	}
2140 
2141 	/*
2142 	 * Bob rolls random k (0 < k < q), computes y = k + b r mod q
2143 	 * and x = g^k mod p, then sends (y, hash(x)) to Alice.
2144 	 */
2145 	bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2146 	sdsa = DSA_SIG_new();
2147 	BN_rand(bk, len * 8, -1, 1);		/* k */
2148 	BN_mod_mul(bn, dsa->priv_key, r, dsa->q, bctx); /* b r mod q */
2149 	BN_add(bn, bn, bk);
2150 	BN_mod(bn, bn, dsa->q, bctx);		/* k + b r mod q */
2151 	sdsa->r = BN_dup(bn);
2152 	BN_mod_exp(bk, dsa->g, bk, dsa->p, bctx); /* g^k mod p */
2153 	bighash(bk, bk);
2154 	sdsa->s = BN_dup(bk);
2155 	BN_CTX_free(bctx);
2156 	BN_free(r); BN_free(bn); BN_free(bk);
2157 
2158 	/*
2159 	 * Encode the values in ASN.1 and sign.
2160 	 */
2161 	tstamp = crypto_time();
2162 	memset(vp, 0, sizeof(struct value));
2163 	vp->tstamp = htonl(tstamp);
2164 	vp->fstamp = htonl(if_fstamp);
2165 	len = i2d_DSA_SIG(sdsa, NULL);
2166 	if (len <= 0) {
2167 		msyslog(LOG_ERR, "crypto_bob %s\n",
2168 		    ERR_error_string(ERR_get_error(), NULL));
2169 		DSA_SIG_free(sdsa);
2170 		return (XEVNT_PUB);
2171 	}
2172 	vp->vallen = htonl(len);
2173 	ptr = emalloc(len);
2174 	vp->ptr = ptr;
2175 	i2d_DSA_SIG(sdsa, &ptr);
2176 	DSA_SIG_free(sdsa);
2177 	vp->siglen = 0;
2178 	if (tstamp == 0)
2179 		return (XEVNT_OK);
2180 	vp->sig = emalloc(sign_siglen);
2181 	EVP_SignInit(&ctx, sign_digest);
2182 	EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2183 	EVP_SignUpdate(&ctx, vp->ptr, len);
2184 	if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2185 		vp->siglen = htonl(len);
2186 	return (XEVNT_OK);
2187 }
2188 
2189 
2190 /*
2191  * crypto_iff - verify Bob's response to Alice's challenge
2192  *
2193  * Returns
2194  * XEVNT_OK	success
2195  * XEVNT_PUB	bad or missing public key
2196  * XEVNT_FSP	bad filestamp
2197  * XEVNT_ID	bad or missing identity parameters
2198  */
2199 int
2200 crypto_iff(
2201 	struct exten *ep,	/* extension pointer */
2202 	struct peer *peer	/* peer structure pointer */
2203 	)
2204 {
2205 	DSA	*dsa;		/* IFF parameters */
2206 	BN_CTX	*bctx;		/* BIGNUM context */
2207 	DSA_SIG	*sdsa;		/* DSA parameters */
2208 	BIGNUM	*bn, *bk;
2209 	u_int	len;
2210 	const u_char	*ptr;
2211 	int	temp;
2212 
2213 	/*
2214 	 * If the IFF parameters are not valid or no challenge was sent,
2215 	 * something awful happened or we are being tormented.
2216 	 */
2217 	if (peer->ident_pkey == NULL) {
2218 		msyslog(LOG_INFO, "crypto_iff: scheme unavailable");
2219 		return (XEVNT_PUB);
2220 	}
2221 	if (ntohl(ep->fstamp) != peer->fstamp) {
2222 		msyslog(LOG_INFO, "crypto_iff: invalid filestamp %u",
2223 		    ntohl(ep->fstamp));
2224 		return (XEVNT_FSP);
2225 	}
2226 	if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
2227 		msyslog(LOG_INFO, "crypto_iff: defective key");
2228 		return (XEVNT_PUB);
2229 	}
2230 	if (peer->iffval == NULL) {
2231 		msyslog(LOG_INFO, "crypto_iff: missing challenge");
2232 		return (XEVNT_PUB);
2233 	}
2234 
2235 	/*
2236 	 * Extract the k + b r and g^k values from the response.
2237 	 */
2238 	bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2239 	len = ntohl(ep->vallen);
2240 	ptr = (const u_char *)ep->pkt;
2241 	if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2242 		msyslog(LOG_ERR, "crypto_iff %s\n",
2243 		    ERR_error_string(ERR_get_error(), NULL));
2244 		return (XEVNT_PUB);
2245 	}
2246 
2247 	/*
2248 	 * Compute g^(k + b r) g^(q - b)r mod p.
2249 	 */
2250 	BN_mod_exp(bn, dsa->pub_key, peer->iffval, dsa->p, bctx);
2251 	BN_mod_exp(bk, dsa->g, sdsa->r, dsa->p, bctx);
2252 	BN_mod_mul(bn, bn, bk, dsa->p, bctx);
2253 
2254 	/*
2255 	 * Verify the hash of the result matches hash(x).
2256 	 */
2257 	bighash(bn, bn);
2258 	temp = BN_cmp(bn, sdsa->s);
2259 	BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
2260 	BN_free(peer->iffval);
2261 	peer->iffval = NULL;
2262 	DSA_SIG_free(sdsa);
2263 	if (temp == 0)
2264 		return (XEVNT_OK);
2265 	else
2266 		return (XEVNT_ID);
2267 }
2268 
2269 
2270 /*
2271  ***********************************************************************
2272  *								       *
2273  * The following routines implement the Guillou-Quisquater (GQ)        *
2274  * identity scheme                                                     *
2275  *								       *
2276  ***********************************************************************
2277  *
2278  * The Guillou-Quisquater (GQ) identity scheme is intended for use when
2279  * the ntp-genkeys program generates the certificates used in the
2280  * protocol and the group key can be conveyed in a certificate extension
2281  * field. The scheme is self contained and independent of new
2282  * generations of host keys, sign keys and certificates.
2283  *
2284  * The GQ identity scheme is based on RSA cryptography and algorithms
2285  * described in Stinson p. 300 (with errors). The GQ values hide in a
2286  * RSA cuckoo structure, but only the modulus is used. The 512-bit
2287  * public modulus is n = p q, where p and q are secret large primes. The
2288  * TA rolls random group key b disguised as a RSA structure member.
2289  * Except for the public key, these values are shared only among group
2290  * members and never revealed in messages.
2291  *
2292  * When rolling new certificates, Bob recomputes the private and
2293  * public keys. The private key u is a random roll, while the public key
2294  * is the inverse obscured by the group key v = (u^-1)^b. These values
2295  * replace the private and public keys normally generated by the RSA
2296  * scheme. Alice challenges Bob to confirm identity using the protocol
2297  * described below.
2298  *
2299  * How it works
2300  *
2301  * The scheme goes like this. Both Alice and Bob have the same modulus n
2302  * and some random b as the group key. These values are computed and
2303  * distributed in advance via secret means, although only the group key
2304  * b is truly secret. Each has a private random private key u and public
2305  * key (u^-1)^b, although not necessarily the same ones. Bob and Alice
2306  * can regenerate the key pair from time to time without affecting
2307  * operations. The public key is conveyed on the certificate in an
2308  * extension field; the private key is never revealed.
2309  *
2310  * Alice rolls new random challenge r and sends to Bob in the GQ
2311  * request message. Bob rolls new random k, then computes y = k u^r mod
2312  * n and x = k^b mod n and sends (y, hash(x)) to Alice in the response
2313  * message. Besides making the response shorter, the hash makes it
2314  * effectivey impossible for an intruder to solve for b by observing
2315  * a number of these messages.
2316  *
2317  * Alice receives the response and computes y^b v^r mod n. After a bit
2318  * of algebra, this simplifies to k^b. If the hash of this result
2319  * matches hash(x), Alice knows that Bob has the group key b. The signed
2320  * response binds this knowledge to Bob's private key and the public key
2321  * previously received in his certificate.
2322  *
2323  * crypto_alice2 - construct Alice's challenge in GQ scheme
2324  *
2325  * Returns
2326  * XEVNT_OK	success
2327  * XEVNT_PUB	bad or missing public key
2328  * XEVNT_ID	bad or missing identity parameters
2329  */
2330 static int
2331 crypto_alice2(
2332 	struct peer *peer,	/* peer pointer */
2333 	struct value *vp	/* value pointer */
2334 	)
2335 {
2336 	RSA	*rsa;		/* GQ parameters */
2337 	BN_CTX	*bctx;		/* BIGNUM context */
2338 	EVP_MD_CTX ctx;		/* signature context */
2339 	tstamp_t tstamp;
2340 	u_int	len;
2341 
2342 	/*
2343 	 * The identity parameters must have correct format and content.
2344 	 */
2345 	if (peer->ident_pkey == NULL)
2346 		return (XEVNT_ID);
2347 	if ((rsa = peer->ident_pkey->pkey.rsa) == NULL) {
2348 		msyslog(LOG_INFO, "crypto_alice2: defective key");
2349 		return (XEVNT_PUB);
2350 	}
2351 
2352 	/*
2353 	 * Roll new random r (0 < r < n). The OpenSSL library has a bug
2354 	 * omitting BN_rand_range, so we have to do it the hard way.
2355 	 */
2356 	bctx = BN_CTX_new();
2357 	len = BN_num_bytes(rsa->n);
2358 	if (peer->iffval != NULL)
2359 		BN_free(peer->iffval);
2360 	peer->iffval = BN_new();
2361 	BN_rand(peer->iffval, len * 8, -1, 1);	/* r mod n */
2362 	BN_mod(peer->iffval, peer->iffval, rsa->n, bctx);
2363 	BN_CTX_free(bctx);
2364 
2365 	/*
2366 	 * Sign and send to Bob. The filestamp is from the local file.
2367 	 */
2368 	tstamp = crypto_time();
2369 	memset(vp, 0, sizeof(struct value));
2370 	vp->tstamp = htonl(tstamp);
2371 	vp->fstamp = htonl(peer->fstamp);
2372 	vp->vallen = htonl(len);
2373 	vp->ptr = emalloc(len);
2374 	BN_bn2bin(peer->iffval, vp->ptr);
2375 	vp->siglen = 0;
2376 	if (tstamp == 0)
2377 		return (XEVNT_OK);
2378 	vp->sig = emalloc(sign_siglen);
2379 	EVP_SignInit(&ctx, sign_digest);
2380 	EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2381 	EVP_SignUpdate(&ctx, vp->ptr, len);
2382 	if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2383 		vp->siglen = htonl(len);
2384 	return (XEVNT_OK);
2385 }
2386 
2387 
2388 /*
2389  * crypto_bob2 - construct Bob's response to Alice's challenge
2390  *
2391  * Returns
2392  * XEVNT_OK	success
2393  * XEVNT_PUB	bad or missing public key
2394  */
2395 static int
2396 crypto_bob2(
2397 	struct exten *ep,	/* extension pointer */
2398 	struct value *vp	/* value pointer */
2399 	)
2400 {
2401 	RSA	*rsa;		/* GQ parameters */
2402 	DSA_SIG	*sdsa;		/* DSA parameters */
2403 	BN_CTX	*bctx;		/* BIGNUM context */
2404 	EVP_MD_CTX ctx;		/* signature context */
2405 	tstamp_t tstamp;	/* NTP timestamp */
2406 	BIGNUM	*r, *k, *g, *y;
2407 	u_char	*ptr;
2408 	u_int	len;
2409 
2410 	/*
2411 	 * If the GQ parameters are not valid, something awful
2412 	 * happened or we are being tormented.
2413 	 */
2414 	if (!(crypto_flags & CRYPTO_FLAG_GQ)) {
2415 		msyslog(LOG_INFO, "crypto_bob2: scheme unavailable");
2416 		return (XEVNT_PUB);
2417 	}
2418 	rsa = gqpar_pkey->pkey.rsa;
2419 
2420 	/*
2421 	 * Extract r from the challenge.
2422 	 */
2423 	len = ntohl(ep->vallen);
2424 	if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2425 		msyslog(LOG_ERR, "crypto_bob2 %s\n",
2426 		    ERR_error_string(ERR_get_error(), NULL));
2427 		return (XEVNT_PUB);
2428 	}
2429 
2430 	/*
2431 	 * Bob rolls random k (0 < k < n), computes y = k u^r mod n and
2432 	 * x = k^b mod n, then sends (y, hash(x)) to Alice.
2433 	 */
2434 	bctx = BN_CTX_new(); k = BN_new(); g = BN_new(); y = BN_new();
2435 	sdsa = DSA_SIG_new();
2436 	BN_rand(k, len * 8, -1, 1);		/* k */
2437 	BN_mod(k, k, rsa->n, bctx);
2438 	BN_mod_exp(y, rsa->p, r, rsa->n, bctx); /* u^r mod n */
2439 	BN_mod_mul(y, k, y, rsa->n, bctx);	/* k u^r mod n */
2440 	sdsa->r = BN_dup(y);
2441 	BN_mod_exp(g, k, rsa->e, rsa->n, bctx); /* k^b mod n */
2442 	bighash(g, g);
2443 	sdsa->s = BN_dup(g);
2444 	BN_CTX_free(bctx);
2445 	BN_free(r); BN_free(k); BN_free(g); BN_free(y);
2446 
2447 	/*
2448 	 * Encode the values in ASN.1 and sign.
2449 	 */
2450 	tstamp = crypto_time();
2451 	memset(vp, 0, sizeof(struct value));
2452 	vp->tstamp = htonl(tstamp);
2453 	vp->fstamp = htonl(gq_fstamp);
2454 	len = i2d_DSA_SIG(sdsa, NULL);
2455 	if (len <= 0) {
2456 		msyslog(LOG_ERR, "crypto_bob2 %s\n",
2457 		    ERR_error_string(ERR_get_error(), NULL));
2458 		DSA_SIG_free(sdsa);
2459 		return (XEVNT_PUB);
2460 	}
2461 	vp->vallen = htonl(len);
2462 	ptr = emalloc(len);
2463 	vp->ptr = ptr;
2464 	i2d_DSA_SIG(sdsa, &ptr);
2465 	DSA_SIG_free(sdsa);
2466 	vp->siglen = 0;
2467 	if (tstamp == 0)
2468 		return (XEVNT_OK);
2469 	vp->sig = emalloc(sign_siglen);
2470 	EVP_SignInit(&ctx, sign_digest);
2471 	EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2472 	EVP_SignUpdate(&ctx, vp->ptr, len);
2473 	if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2474 		vp->siglen = htonl(len);
2475 	return (XEVNT_OK);
2476 }
2477 
2478 
2479 /*
2480  * crypto_gq - verify Bob's response to Alice's challenge
2481  *
2482  * Returns
2483  * XEVNT_OK	success
2484  * XEVNT_PUB	bad or missing public key
2485  * XEVNT_FSP	bad filestamp
2486  * XEVNT_ID	bad or missing identity parameters
2487  */
2488 int
2489 crypto_gq(
2490 	struct exten *ep,	/* extension pointer */
2491 	struct peer *peer	/* peer structure pointer */
2492 	)
2493 {
2494 	RSA	*rsa;		/* GQ parameters */
2495 	BN_CTX	*bctx;		/* BIGNUM context */
2496 	DSA_SIG	*sdsa;		/* RSA signature context fake */
2497 	BIGNUM	*y, *v;
2498 	const u_char	*ptr;
2499 	u_int	len;
2500 	int	temp;
2501 
2502 	/*
2503 	 * If the GQ parameters are not valid or no challenge was sent,
2504 	 * something awful happened or we are being tormented.
2505 	 */
2506 	if (peer->ident_pkey == NULL) {
2507 		msyslog(LOG_INFO, "crypto_gq: scheme unavailable");
2508 		return (XEVNT_PUB);
2509 	}
2510 	if (ntohl(ep->fstamp) != peer->fstamp) {
2511 		msyslog(LOG_INFO, "crypto_gq: invalid filestamp %u",
2512 		    ntohl(ep->fstamp));
2513 		return (XEVNT_FSP);
2514 	}
2515 	if ((rsa = peer->ident_pkey->pkey.rsa) == NULL) {
2516 		msyslog(LOG_INFO, "crypto_gq: defective key");
2517 		return (XEVNT_PUB);
2518 	}
2519 	if (peer->iffval == NULL) {
2520 		msyslog(LOG_INFO, "crypto_gq: missing challenge");
2521 		return (XEVNT_PUB);
2522 	}
2523 
2524 	/*
2525 	 * Extract the y = k u^r and hash(x = k^b) values from the
2526 	 * response.
2527 	 */
2528 	bctx = BN_CTX_new(); y = BN_new(); v = BN_new();
2529 	len = ntohl(ep->vallen);
2530 	ptr = (const u_char *)ep->pkt;
2531 	if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2532 		msyslog(LOG_ERR, "crypto_gq %s\n",
2533 		    ERR_error_string(ERR_get_error(), NULL));
2534 		return (XEVNT_PUB);
2535 	}
2536 
2537 	/*
2538 	 * Compute v^r y^b mod n.
2539 	 */
2540 	BN_mod_exp(v, peer->grpkey, peer->iffval, rsa->n, bctx);
2541 						/* v^r mod n */
2542 	BN_mod_exp(y, sdsa->r, rsa->e, rsa->n, bctx); /* y^b mod n */
2543 	BN_mod_mul(y, v, y, rsa->n, bctx);	/* v^r y^b mod n */
2544 
2545 	/*
2546 	 * Verify the hash of the result matches hash(x).
2547 	 */
2548 	bighash(y, y);
2549 	temp = BN_cmp(y, sdsa->s);
2550 	BN_CTX_free(bctx); BN_free(y); BN_free(v);
2551 	BN_free(peer->iffval);
2552 	peer->iffval = NULL;
2553 	DSA_SIG_free(sdsa);
2554 	if (temp == 0)
2555 		return (XEVNT_OK);
2556 	else
2557 		return (XEVNT_ID);
2558 }
2559 
2560 
2561 /*
2562  ***********************************************************************
2563  *								       *
2564  * The following routines implement the Mu-Varadharajan (MV) identity  *
2565  * scheme                                                              *
2566  *								       *
2567  ***********************************************************************
2568  */
2569 /*
2570  * The Mu-Varadharajan (MV) cryptosystem was originally intended when
2571  * servers broadcast messages to clients, but clients never send
2572  * messages to servers. There is one encryption key for the server and a
2573  * separate decryption key for each client. It operated something like a
2574  * pay-per-view satellite broadcasting system where the session key is
2575  * encrypted by the broadcaster and the decryption keys are held in a
2576  * tamperproof set-top box.
2577  *
2578  * The MV parameters and private encryption key hide in a DSA cuckoo
2579  * structure which uses the same parameters, but generated in a
2580  * different way. The values are used in an encryption scheme similar to
2581  * El Gamal cryptography and a polynomial formed from the expansion of
2582  * product terms (x - x[j]), as described in Mu, Y., and V.
2583  * Varadharajan: Robust and Secure Broadcasting, Proc. Indocrypt 2001,
2584  * 223-231. The paper has significant errors and serious omissions.
2585  *
2586  * Let q be the product of n distinct primes s'[j] (j = 1...n), where
2587  * each s'[j] has m significant bits. Let p be a prime p = 2 * q + 1, so
2588  * that q and each s'[j] divide p - 1 and p has M = n * m + 1
2589  * significant bits. The elements x mod q of Zq with the elements 2 and
2590  * the primes removed form a field Zq* valid for polynomial arithetic.
2591  * Let g be a generator of Zp; that is, gcd(g, p - 1) = 1 and g^q = 1
2592  * mod p. We expect M to be in the 500-bit range and n relatively small,
2593  * like 25, so the likelihood of a randomly generated element of x mod q
2594  * of Zq colliding with a factor of p - 1 is very small and can be
2595  * avoided. Associated with each s'[j] is an element s[j] such that s[j]
2596  * s'[j] = s'[j] mod q. We find s[j] as the quotient (q + s'[j]) /
2597  * s'[j]. These are the parameters of the scheme and they are expensive
2598  * to compute.
2599  *
2600  * We set up an instance of the scheme as follows. A set of random
2601  * values x[j] mod q (j = 1...n), are generated as the zeros of a
2602  * polynomial of order n. The product terms (x - x[j]) are expanded to
2603  * form coefficients a[i] mod q (i = 0...n) in powers of x. These are
2604  * used as exponents of the generator g mod p to generate the private
2605  * encryption key A. The pair (gbar, ghat) of public server keys and the
2606  * pairs (xbar[j], xhat[j]) (j = 1...n) of private client keys are used
2607  * to construct the decryption keys. The devil is in the details.
2608  *
2609  * The distinguishing characteristic of this scheme is the capability to
2610  * revoke keys. Included in the calculation of E, gbar and ghat is the
2611  * product s = prod(s'[j]) (j = 1...n) above. If the factor s'[j] is
2612  * subsequently removed from the product and E, gbar and ghat
2613  * recomputed, the jth client will no longer be able to compute E^-1 and
2614  * thus unable to decrypt the block.
2615  *
2616  * How it works
2617  *
2618  * The scheme goes like this. Bob has the server values (p, A, q, gbar,
2619  * ghat) and Alice the client values (p, xbar, xhat).
2620  *
2621  * Alice rolls new random challenge r (0 < r < p) and sends to Bob in
2622  * the MV request message. Bob rolls new random k (0 < k < q), encrypts
2623  * y = A^k mod p (a permutation) and sends (hash(y), gbar^k, ghat^k) to
2624  * Alice.
2625  *
2626  * Alice receives the response and computes the decryption key (the
2627  * inverse permutation) from previously obtained (xbar, xhat) and
2628  * (gbar^k, ghat^k) in the message. She computes the inverse, which is
2629  * unique by reasons explained in the ntp-keygen.c program sources. If
2630  * the hash of this result matches hash(y), Alice knows that Bob has the
2631  * group key b. The signed response binds this knowledge to Bob's
2632  * private key and the public key previously received in his
2633  * certificate.
2634  *
2635  * crypto_alice3 - construct Alice's challenge in MV scheme
2636  *
2637  * Returns
2638  * XEVNT_OK	success
2639  * XEVNT_PUB	bad or missing public key
2640  * XEVNT_ID	bad or missing identity parameters
2641  */
2642 static int
2643 crypto_alice3(
2644 	struct peer *peer,	/* peer pointer */
2645 	struct value *vp	/* value pointer */
2646 	)
2647 {
2648 	DSA	*dsa;		/* MV parameters */
2649 	BN_CTX	*bctx;		/* BIGNUM context */
2650 	EVP_MD_CTX ctx;		/* signature context */
2651 	tstamp_t tstamp;
2652 	u_int	len;
2653 
2654 	/*
2655 	 * The identity parameters must have correct format and content.
2656 	 */
2657 	if (peer->ident_pkey == NULL)
2658 		return (XEVNT_ID);
2659 	if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
2660 		msyslog(LOG_INFO, "crypto_alice3: defective key");
2661 		return (XEVNT_PUB);
2662 	}
2663 
2664 	/*
2665 	 * Roll new random r (0 < r < q). The OpenSSL library has a bug
2666 	 * omitting BN_rand_range, so we have to do it the hard way.
2667 	 */
2668 	bctx = BN_CTX_new();
2669 	len = BN_num_bytes(dsa->p);
2670 	if (peer->iffval != NULL)
2671 		BN_free(peer->iffval);
2672 	peer->iffval = BN_new();
2673 	BN_rand(peer->iffval, len * 8, -1, 1);	/* r */
2674 	BN_mod(peer->iffval, peer->iffval, dsa->p, bctx);
2675 	BN_CTX_free(bctx);
2676 
2677 	/*
2678 	 * Sign and send to Bob. The filestamp is from the local file.
2679 	 */
2680 	tstamp = crypto_time();
2681 	memset(vp, 0, sizeof(struct value));
2682 	vp->tstamp = htonl(tstamp);
2683 	vp->fstamp = htonl(peer->fstamp);
2684 	vp->vallen = htonl(len);
2685 	vp->ptr = emalloc(len);
2686 	BN_bn2bin(peer->iffval, vp->ptr);
2687 	vp->siglen = 0;
2688 	if (tstamp == 0)
2689 		return (XEVNT_OK);
2690 	vp->sig = emalloc(sign_siglen);
2691 	EVP_SignInit(&ctx, sign_digest);
2692 	EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2693 	EVP_SignUpdate(&ctx, vp->ptr, len);
2694 	if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2695 		vp->siglen = htonl(len);
2696 	return (XEVNT_OK);
2697 }
2698 
2699 
2700 /*
2701  * crypto_bob3 - construct Bob's response to Alice's challenge
2702  *
2703  * Returns
2704  * XEVNT_OK	success
2705  * XEVNT_PUB	bad or missing public key
2706  */
2707 static int
2708 crypto_bob3(
2709 	struct exten *ep,	/* extension pointer */
2710 	struct value *vp	/* value pointer */
2711 	)
2712 {
2713 	DSA	*dsa;		/* MV parameters */
2714 	DSA	*sdsa;		/* DSA signature context fake */
2715 	BN_CTX	*bctx;		/* BIGNUM context */
2716 	EVP_MD_CTX ctx;		/* signature context */
2717 	tstamp_t tstamp;	/* NTP timestamp */
2718 	BIGNUM	*r, *k, *u;
2719 	u_char	*ptr;
2720 	u_int	len;
2721 
2722 	/*
2723 	 * If the MV parameters are not valid, something awful
2724 	 * happened or we are being tormented.
2725 	 */
2726 	if (!(crypto_flags & CRYPTO_FLAG_MV)) {
2727 		msyslog(LOG_INFO, "crypto_bob3: scheme unavailable");
2728 		return (XEVNT_PUB);
2729 	}
2730 	dsa = mvpar_pkey->pkey.dsa;
2731 
2732 	/*
2733 	 * Extract r from the challenge.
2734 	 */
2735 	len = ntohl(ep->vallen);
2736 	if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2737 		msyslog(LOG_ERR, "crypto_bob3 %s\n",
2738 		    ERR_error_string(ERR_get_error(), NULL));
2739 		return (XEVNT_PUB);
2740 	}
2741 
2742 	/*
2743 	 * Bob rolls random k (0 < k < q), making sure it is not a
2744 	 * factor of q. He then computes y = A^k r and sends (hash(y),
2745 	 * gbar^k, ghat^k) to Alice.
2746 	 */
2747 	bctx = BN_CTX_new(); k = BN_new(); u = BN_new();
2748 	sdsa = DSA_new();
2749 	sdsa->p = BN_new(); sdsa->q = BN_new(); sdsa->g = BN_new();
2750 	while (1) {
2751 		BN_rand(k, BN_num_bits(dsa->q), 0, 0);
2752 		BN_mod(k, k, dsa->q, bctx);
2753 		BN_gcd(u, k, dsa->q, bctx);
2754 		if (BN_is_one(u))
2755 			break;
2756 	}
2757 	BN_mod_exp(u, dsa->g, k, dsa->p, bctx); /* A r */
2758 	BN_mod_mul(u, u, r, dsa->p, bctx);
2759 	bighash(u, sdsa->p);
2760 	BN_mod_exp(sdsa->q, dsa->priv_key, k, dsa->p, bctx); /* gbar */
2761 	BN_mod_exp(sdsa->g, dsa->pub_key, k, dsa->p, bctx); /* ghat */
2762 	BN_CTX_free(bctx); BN_free(k); BN_free(r); BN_free(u);
2763 
2764 	/*
2765 	 * Encode the values in ASN.1 and sign.
2766 	 */
2767 	tstamp = crypto_time();
2768 	memset(vp, 0, sizeof(struct value));
2769 	vp->tstamp = htonl(tstamp);
2770 	vp->fstamp = htonl(mv_fstamp);
2771 	len = i2d_DSAparams(sdsa, NULL);
2772 	if (len <= 0) {
2773 		msyslog(LOG_ERR, "crypto_bob3 %s\n",
2774 		    ERR_error_string(ERR_get_error(), NULL));
2775 		DSA_free(sdsa);
2776 		return (XEVNT_PUB);
2777 	}
2778 	vp->vallen = htonl(len);
2779 	ptr = emalloc(len);
2780 	vp->ptr = ptr;
2781 	i2d_DSAparams(sdsa, &ptr);
2782 	DSA_free(sdsa);
2783 	vp->siglen = 0;
2784 	if (tstamp == 0)
2785 		return (XEVNT_OK);
2786 	vp->sig = emalloc(sign_siglen);
2787 	EVP_SignInit(&ctx, sign_digest);
2788 	EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2789 	EVP_SignUpdate(&ctx, vp->ptr, len);
2790 	if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2791 		vp->siglen = htonl(len);
2792 	return (XEVNT_OK);
2793 }
2794 
2795 
2796 /*
2797  * crypto_mv - verify Bob's response to Alice's challenge
2798  *
2799  * Returns
2800  * XEVNT_OK	success
2801  * XEVNT_PUB	bad or missing public key
2802  * XEVNT_FSP	bad filestamp
2803  * XEVNT_ID	bad or missing identity parameters
2804  */
2805 int
2806 crypto_mv(
2807 	struct exten *ep,	/* extension pointer */
2808 	struct peer *peer	/* peer structure pointer */
2809 	)
2810 {
2811 	DSA	*dsa;		/* MV parameters */
2812 	DSA	*sdsa;		/* DSA parameters */
2813 	BN_CTX	*bctx;		/* BIGNUM context */
2814 	BIGNUM	*k, *u, *v;
2815 	u_int	len;
2816 	const u_char	*ptr;
2817 	int	temp;
2818 
2819 	/*
2820 	 * If the MV parameters are not valid or no challenge was sent,
2821 	 * something awful happened or we are being tormented.
2822 	 */
2823 	if (peer->ident_pkey == NULL) {
2824 		msyslog(LOG_INFO, "crypto_mv: scheme unavailable");
2825 		return (XEVNT_PUB);
2826 	}
2827 	if (ntohl(ep->fstamp) != peer->fstamp) {
2828 		msyslog(LOG_INFO, "crypto_mv: invalid filestamp %u",
2829 		    ntohl(ep->fstamp));
2830 		return (XEVNT_FSP);
2831 	}
2832 	if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
2833 		msyslog(LOG_INFO, "crypto_mv: defective key");
2834 		return (XEVNT_PUB);
2835 	}
2836 	if (peer->iffval == NULL) {
2837 		msyslog(LOG_INFO, "crypto_mv: missing challenge");
2838 		return (XEVNT_PUB);
2839 	}
2840 
2841 	/*
2842 	 * Extract the (hash(y), gbar, ghat) values from the response.
2843 	 */
2844 	bctx = BN_CTX_new(); k = BN_new(); u = BN_new(); v = BN_new();
2845 	len = ntohl(ep->vallen);
2846 	ptr = (const u_char *)ep->pkt;
2847 	if ((sdsa = d2i_DSAparams(NULL, &ptr, len)) == NULL) {
2848 		msyslog(LOG_ERR, "crypto_mv %s\n",
2849 		    ERR_error_string(ERR_get_error(), NULL));
2850 		return (XEVNT_PUB);
2851 	}
2852 
2853 	/*
2854 	 * Compute (gbar^xhat ghat^xbar)^-1 mod p.
2855 	 */
2856 	BN_mod_exp(u, sdsa->q, dsa->pub_key, dsa->p, bctx);
2857 	BN_mod_exp(v, sdsa->g, dsa->priv_key, dsa->p, bctx);
2858 	BN_mod_mul(u, u, v, dsa->p, bctx);
2859 	BN_mod_inverse(u, u, dsa->p, bctx);
2860 	BN_mod_mul(v, u, peer->iffval, dsa->p, bctx);
2861 
2862 	/*
2863 	 * The result should match the hash of r mod p.
2864 	 */
2865 	bighash(v, v);
2866 	temp = BN_cmp(v, sdsa->p);
2867 	BN_CTX_free(bctx); BN_free(k); BN_free(u); BN_free(v);
2868 	BN_free(peer->iffval);
2869 	peer->iffval = NULL;
2870 	DSA_free(sdsa);
2871 	if (temp == 0)
2872 		return (XEVNT_OK);
2873 	else
2874 		return (XEVNT_ID);
2875 }
2876 
2877 
2878 /*
2879  ***********************************************************************
2880  *								       *
2881  * The following routines are used to manipulate certificates          *
2882  *								       *
2883  ***********************************************************************
2884  */
2885 /*
2886  * cert_parse - parse x509 certificate and create info/value structures.
2887  *
2888  * The server certificate includes the version number, issuer name,
2889  * subject name, public key and valid date interval. If the issuer name
2890  * is the same as the subject name, the certificate is self signed and
2891  * valid only if the server is configured as trustable. If the names are
2892  * different, another issuer has signed the server certificate and
2893  * vouched for it. In this case the server certificate is valid if
2894  * verified by the issuer public key.
2895  *
2896  * Returns certificate info/value pointer if valid, NULL if not.
2897  */
2898 struct cert_info *		/* certificate information structure */
2899 cert_parse(
2900 	u_char	*asn1cert,	/* X509 certificate */
2901 	u_int	len,		/* certificate length */
2902 	tstamp_t fstamp		/* filestamp */
2903 	)
2904 {
2905 	X509	*cert;		/* X509 certificate */
2906 	X509_EXTENSION *ext;	/* X509v3 extension */
2907 	struct cert_info *ret;	/* certificate info/value */
2908 	BIO	*bp;
2909 	X509V3_EXT_METHOD *method;
2910 	char	pathbuf[MAXFILENAME];
2911 	u_char	*uptr;
2912 	char	*ptr;
2913 	int	temp, cnt, i;
2914 
2915 	/*
2916 	 * Decode ASN.1 objects and construct certificate structure.
2917 	 */
2918 	uptr = asn1cert;
2919 	if ((cert = d2i_X509(NULL, &uptr, len)) == NULL) {
2920 		msyslog(LOG_ERR, "cert_parse %s\n",
2921 		    ERR_error_string(ERR_get_error(), NULL));
2922 		return (NULL);
2923 	}
2924 
2925 	/*
2926 	 * Extract version, subject name and public key.
2927 	 */
2928 	ret = emalloc(sizeof(struct cert_info));
2929 	memset(ret, 0, sizeof(struct cert_info));
2930 	if ((ret->pkey = X509_get_pubkey(cert)) == NULL) {
2931 		msyslog(LOG_ERR, "cert_parse %s\n",
2932 		    ERR_error_string(ERR_get_error(), NULL));
2933 		cert_free(ret);
2934 		X509_free(cert);
2935 		return (NULL);
2936 	}
2937 	ret->version = X509_get_version(cert);
2938 	X509_NAME_oneline(X509_get_subject_name(cert), pathbuf,
2939 	    MAXFILENAME - 1);
2940 	ptr = strstr(pathbuf, "CN=");
2941 	if (ptr == NULL) {
2942 		msyslog(LOG_INFO, "cert_parse: invalid subject %s",
2943 		    pathbuf);
2944 		cert_free(ret);
2945 		X509_free(cert);
2946 		return (NULL);
2947 	}
2948 	ret->subject = emalloc(strlen(ptr) + 1);
2949 	strcpy(ret->subject, ptr + 3);
2950 
2951 	/*
2952 	 * Extract remaining objects. Note that the NTP serial number is
2953 	 * the NTP seconds at the time of signing, but this might not be
2954 	 * the case for other authority. We don't bother to check the
2955 	 * objects at this time, since the real crunch can happen only
2956 	 * when the time is valid but not yet certificated.
2957 	 */
2958 	ret->nid = OBJ_obj2nid(cert->cert_info->signature->algorithm);
2959 	ret->digest = (const EVP_MD *)EVP_get_digestbynid(ret->nid);
2960 	ret->serial =
2961 	    (u_long)ASN1_INTEGER_get(X509_get_serialNumber(cert));
2962 	X509_NAME_oneline(X509_get_issuer_name(cert), pathbuf,
2963 	    MAXFILENAME);
2964 	if ((ptr = strstr(pathbuf, "CN=")) == NULL) {
2965 		msyslog(LOG_INFO, "cert_parse: invalid issuer %s",
2966 		    pathbuf);
2967 		cert_free(ret);
2968 		X509_free(cert);
2969 		return (NULL);
2970 	}
2971 	ret->issuer = emalloc(strlen(ptr) + 1);
2972 	strcpy(ret->issuer, ptr + 3);
2973 	ret->first = asn2ntp(X509_get_notBefore(cert));
2974 	ret->last = asn2ntp(X509_get_notAfter(cert));
2975 
2976 	/*
2977 	 * Extract extension fields. These are ad hoc ripoffs of
2978 	 * currently assigned functions and will certainly be changed
2979 	 * before prime time.
2980 	 */
2981 	cnt = X509_get_ext_count(cert);
2982 	for (i = 0; i < cnt; i++) {
2983 		ext = X509_get_ext(cert, i);
2984 		method = X509V3_EXT_get(ext);
2985 		temp = OBJ_obj2nid(ext->object);
2986 		switch (temp) {
2987 
2988 		/*
2989 		 * If a key_usage field is present, we decode whether
2990 		 * this is a trusted or private certificate. This is
2991 		 * dorky; all we want is to compare NIDs, but OpenSSL
2992 		 * insists on BIO text strings.
2993 		 */
2994 		case NID_ext_key_usage:
2995 			bp = BIO_new(BIO_s_mem());
2996 			X509V3_EXT_print(bp, ext, 0, 0);
2997 			BIO_gets(bp, pathbuf, MAXFILENAME);
2998 			BIO_free(bp);
2999 #if DEBUG
3000 			if (debug)
3001 				printf("cert_parse: %s: %s\n",
3002 				    OBJ_nid2ln(temp), pathbuf);
3003 #endif
3004 			if (strcmp(pathbuf, "Trust Root") == 0)
3005 				ret->flags |= CERT_TRUST;
3006 			else if (strcmp(pathbuf, "Private") == 0)
3007 				ret->flags |= CERT_PRIV;
3008 			break;
3009 
3010 		/*
3011 		 * If a NID_subject_key_identifier field is present, it
3012 		 * contains the GQ public key.
3013 		 */
3014 		case NID_subject_key_identifier:
3015 			ret->grplen = ext->value->length - 2;
3016 			ret->grpkey = emalloc(ret->grplen);
3017 			memcpy(ret->grpkey, &ext->value->data[2],
3018 			    ret->grplen);
3019 			break;
3020 		}
3021 	}
3022 
3023 	/*
3024 	 * If certificate is self signed, verify signature.
3025 	 */
3026 	if (strcmp(ret->subject, ret->issuer) == 0) {
3027 		if (!X509_verify(cert, ret->pkey)) {
3028 			msyslog(LOG_INFO,
3029 			    "cert_parse: invalid signature not verified %s",
3030 			    pathbuf);
3031 			cert_free(ret);
3032 			X509_free(cert);
3033 			return (NULL);
3034 		}
3035 	}
3036 
3037 	/*
3038 	 * Verify certificate valid times. Note that certificates cannot
3039 	 * be retroactive.
3040 	 */
3041 	if (ret->first > ret->last || ret->first < fstamp) {
3042 		msyslog(LOG_INFO,
3043 		    "cert_parse: expired %s",
3044 		    ret->subject);
3045 		cert_free(ret);
3046 		X509_free(cert);
3047 		return (NULL);
3048 	}
3049 
3050 	/*
3051 	 * Build the value structure to sign and send later.
3052 	 */
3053 	ret->cert.fstamp = htonl(fstamp);
3054 	ret->cert.vallen = htonl(len);
3055 	ret->cert.ptr = emalloc(len);
3056 	memcpy(ret->cert.ptr, asn1cert, len);
3057 #ifdef DEBUG
3058 	if (debug > 1)
3059 		X509_print_fp(stdout, cert);
3060 #endif
3061 	X509_free(cert);
3062 	return (ret);
3063 }
3064 
3065 
3066 /*
3067  * cert_sign - sign x509 certificate and update value structure.
3068  *
3069  * The certificate request is a copy of the client certificate, which
3070  * includes the version number, subject name and public key of the
3071  * client. The resulting certificate includes these values plus the
3072  * serial number, issuer name and validity interval of the server. The
3073  * validity interval extends from the current time to the same time one
3074  * year hence. For NTP purposes, it is convenient to use the NTP seconds
3075  * of the current time as the serial number.
3076  *
3077  * Returns
3078  * XEVNT_OK	success
3079  * XEVNT_PUB	bad or missing public key
3080  * XEVNT_CRT	bad or missing certificate
3081  * XEVNT_VFY	certificate not verified
3082  */
3083 static int
3084 cert_sign(
3085 	struct exten *ep,	/* extension field pointer */
3086 	struct value *vp	/* value pointer */
3087 	)
3088 {
3089 	X509	*req;		/* X509 certificate request */
3090 	X509	*cert;		/* X509 certificate */
3091 	X509_EXTENSION *ext;	/* certificate extension */
3092 	ASN1_INTEGER *serial;	/* serial number */
3093 	X509_NAME *subj;	/* distinguished (common) name */
3094 	EVP_PKEY *pkey;		/* public key */
3095 	EVP_MD_CTX ctx;		/* message digest context */
3096 	tstamp_t tstamp;	/* NTP timestamp */
3097 	u_int	len;
3098 	u_char	*ptr;
3099 	int	i, temp;
3100 
3101 	/*
3102 	 * Decode ASN.1 objects and construct certificate structure.
3103 	 */
3104 	tstamp = crypto_time();
3105 	if (tstamp == 0)
3106 		return (XEVNT_TSP);
3107 
3108 	ptr = (u_char *)ep->pkt;
3109 	if ((req = d2i_X509(NULL, &ptr, ntohl(ep->vallen))) == NULL) {
3110 		msyslog(LOG_ERR, "cert_sign %s\n",
3111 		    ERR_error_string(ERR_get_error(), NULL));
3112 		return (XEVNT_CRT);
3113 	}
3114 	/*
3115 	 * Extract public key and check for errors.
3116 	 */
3117 	if ((pkey = X509_get_pubkey(req)) == NULL) {
3118 		msyslog(LOG_ERR, "cert_sign %s\n",
3119 		    ERR_error_string(ERR_get_error(), NULL));
3120 		X509_free(req);
3121 		return (XEVNT_PUB);
3122 	}
3123 
3124 	/*
3125 	 * Generate X509 certificate signed by this server. For this
3126 	 * prupose the issuer name is the server name. Also copy any
3127 	 * extensions that might be present.
3128 	 */
3129 	cert = X509_new();
3130 	X509_set_version(cert, X509_get_version(req));
3131 	serial = ASN1_INTEGER_new();
3132 	ASN1_INTEGER_set(serial, tstamp);
3133 	X509_set_serialNumber(cert, serial);
3134 	X509_gmtime_adj(X509_get_notBefore(cert), 0L);
3135 	X509_gmtime_adj(X509_get_notAfter(cert), YEAR);
3136 	subj = X509_get_issuer_name(cert);
3137 	X509_NAME_add_entry_by_txt(subj, "commonName", MBSTRING_ASC,
3138 	    (unsigned char *) sys_hostname, strlen(sys_hostname), -1, 0);
3139 	subj = X509_get_subject_name(req);
3140 	X509_set_subject_name(cert, subj);
3141 	X509_set_pubkey(cert, pkey);
3142 	ext = X509_get_ext(req, 0);
3143 	temp = X509_get_ext_count(req);
3144 	for (i = 0; i < temp; i++) {
3145 		ext = X509_get_ext(req, i);
3146 		X509_add_ext(cert, ext, -1);
3147 	}
3148 	X509_free(req);
3149 
3150 	/*
3151 	 * Sign and verify the certificate.
3152 	 */
3153 	X509_sign(cert, sign_pkey, sign_digest);
3154 	if (!X509_verify(cert, sign_pkey)) {
3155 		printf("cert_sign\n%s\n",
3156 		    ERR_error_string(ERR_get_error(), NULL));
3157 		X509_free(cert);
3158 		return (XEVNT_VFY);
3159 	}
3160 	len = i2d_X509(cert, NULL);
3161 
3162 	/*
3163 	 * Build and sign the value structure. We have to sign it here,
3164 	 * since the response has to be returned right away. This is a
3165 	 * clogging hazard.
3166 	 */
3167 	memset(vp, 0, sizeof(struct value));
3168 	vp->tstamp = htonl(tstamp);
3169 	vp->fstamp = ep->fstamp;
3170 	vp->vallen = htonl(len);
3171 	vp->ptr = emalloc(len);
3172 	ptr = vp->ptr;
3173 	i2d_X509(cert, &ptr);
3174 	vp->siglen = 0;
3175 	vp->sig = emalloc(sign_siglen);
3176 	EVP_SignInit(&ctx, sign_digest);
3177 	EVP_SignUpdate(&ctx, (u_char *)vp, 12);
3178 	EVP_SignUpdate(&ctx, vp->ptr, len);
3179 	if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
3180 		vp->siglen = htonl(len);
3181 #ifdef DEBUG
3182 	if (debug > 1)
3183 		X509_print_fp(stdout, cert);
3184 #endif
3185 	X509_free(cert);
3186 	return (XEVNT_OK);
3187 }
3188 
3189 
3190 /*
3191  * cert_valid - verify certificate with given public key
3192  *
3193  * This is pretty ugly, as the certificate has to be verified in the
3194  * OpenSSL X509 structure, not in the DER format in the info/value
3195  * structure.
3196  *
3197  * Returns
3198  * XEVNT_OK	success
3199  * XEVNT_VFY	certificate not verified
3200  */
3201 int
3202 cert_valid(
3203 	struct cert_info *cinf,	/* certificate information structure */
3204 	EVP_PKEY *pkey		/* public key */
3205 	)
3206 {
3207 	X509	*cert;		/* X509 certificate */
3208 	u_char	*ptr;
3209 
3210 	if (cinf->flags & CERT_SIGN)
3211 		return (XEVNT_OK);
3212 	ptr = (u_char *)cinf->cert.ptr;
3213 	cert = d2i_X509(NULL, &ptr, ntohl(cinf->cert.vallen));
3214 	if (!X509_verify(cert, pkey))
3215 		return (XEVNT_VFY);
3216 	cinf->flags |= CERT_SIGN;
3217 	X509_free(cert);
3218 	return (XEVNT_OK);
3219 }
3220 
3221 
3222 /*
3223  * cert - install certificate in certificate list
3224  *
3225  * This routine encodes an extension field into a certificate info/value
3226  * structure. It searches the certificate list for duplicates and
3227  * expunges whichever is older. It then searches the list for other
3228  * certificates that might be verified by this latest one. Finally, it
3229  * inserts this certificate first on the list.
3230  *
3231  * Returns
3232  * XEVNT_OK	success
3233  * XEVNT_PER	certificate expired
3234  * XEVNT_CRT	bad or missing certificate
3235  */
3236 int
3237 cert_install(
3238 	struct exten *ep,	/* cert info/value */
3239 	struct peer *peer	/* peer structure */
3240 	)
3241 {
3242 	struct cert_info *cp, *xp, *yp, **zp;
3243 	int	rval;
3244 	tstamp_t tstamp;
3245 
3246 	/*
3247 	 * Parse and validate the signed certificate. If valid,
3248 	 * construct the info/value structure; otherwise, scamper home.
3249 	 * Note this allows a certificate not-before time to be in the
3250 	 * future, but not a not-after time to be in the past.
3251 	 */
3252 	if ((cp = cert_parse((u_char *)ep->pkt, ntohl(ep->vallen),
3253 	    ntohl(ep->fstamp))) == NULL)
3254 		return (XEVNT_CRT);
3255 
3256 	tstamp = crypto_time();
3257 	if (tstamp > cp->last) {
3258 		cert_free(cp);
3259 		return (XEVNT_PER);
3260 	}
3261 
3262 	/*
3263 	 * Scan certificate list looking for another certificate with
3264 	 * the same subject and issuer. If another is found with the
3265 	 * same or older filestamp, unlink it and return the goodies to
3266 	 * the heap. If another is found with a later filetsamp, discard
3267 	 * the new one and leave the building.
3268 	 */
3269 	rval = XEVNT_OK;
3270 	yp = cp;
3271 	zp = &cinfo;
3272 	for (xp = cinfo; xp != NULL; xp = xp->link) {
3273 		if (strcmp(cp->subject, xp->subject) == 0 &&
3274 		    strcmp(cp->issuer, xp->issuer) == 0) {
3275 			if (ntohl(cp->cert.fstamp) <=
3276 			    ntohl(xp->cert.fstamp)) {
3277 				*zp = xp->link;;
3278 				cert_free(xp);
3279 			} else {
3280 				cert_free(cp);
3281 				return (XEVNT_TSP);
3282 			}
3283 			break;
3284 		}
3285 		zp = &xp->link;
3286 	}
3287 	yp->link = cinfo;
3288 	cinfo = yp;
3289 
3290 	/*
3291 	 * Scan the certificate list to see if Y is signed by X.
3292 	 */
3293 	for (yp = cinfo; yp != NULL; yp = yp->link) {
3294 		for (xp = cinfo; xp != NULL; xp = xp->link) {
3295 			if (yp->flags & CERT_ERROR)
3296 				continue;
3297 
3298 			/*
3299 			 * If issuer Y matches subject X and signature Y
3300 			 * is valid using public key X, then Y is valid.
3301 			 */
3302 			if (strcmp(yp->issuer, xp->subject) != 0)
3303 				continue;
3304 
3305 			if (cert_valid(yp, xp->pkey) != XEVNT_OK) {
3306 				yp->flags |= CERT_ERROR;
3307 				continue;
3308 			}
3309 			xp->flags |= CERT_SIGN;
3310 
3311 			/*
3312 			 * If X is trusted, then Y is trusted. Note that
3313 			 * we might stumble over a self signed
3314 			 * certificate that is not trusted, at least
3315 			 * temporarily. This can happen when a dude
3316 			 * first comes up, but has not synchronized the
3317 			 * clock and had its certificate signed by its
3318 			 * server. In case of broken certificate trail,
3319 			 * this might result in a loop that could
3320 			 * persist until timeout.
3321 			 */
3322 			if (!(xp->flags & CERT_TRUST))
3323 				continue;
3324 
3325 			yp->flags |= CERT_TRUST;
3326 
3327 			/*
3328 			 * If subject Y matches the server subject name,
3329 			 * then Y has completed the certificate trail.
3330 			 * Save the group key and light the valid bit.
3331 			 */
3332 			if (strcmp(yp->subject, peer->subject) != 0)
3333 				continue;
3334 
3335 			if (yp->grpkey != NULL) {
3336 				if (peer->grpkey != NULL)
3337 					BN_free(peer->grpkey);
3338 				peer->grpkey = BN_bin2bn(yp->grpkey,
3339 				     yp->grplen, NULL);
3340 			}
3341 			peer->crypto |= CRYPTO_FLAG_VALID;
3342 
3343 			/*
3344 			 * If the server has an an identity scheme,
3345 			 * fetch the identity credentials. If not, the
3346 			 * identity is verified only by the trusted
3347 			 * certificate. The next signature will set the
3348 			 * server proventic.
3349 			 */
3350 			if (peer->crypto & (CRYPTO_FLAG_GQ |
3351 			    CRYPTO_FLAG_IFF | CRYPTO_FLAG_MV))
3352 				continue;
3353 
3354 			peer->crypto |= CRYPTO_FLAG_VRFY;
3355 		}
3356 	}
3357 
3358 	/*
3359 	 * That was awesome. Now update the timestamps and signatures.
3360 	 */
3361 	crypto_update();
3362 	return (rval);
3363 }
3364 
3365 
3366 /*
3367  * cert_free - free certificate information structure
3368  */
3369 void
3370 cert_free(
3371 	struct cert_info *cinf	/* certificate info/value structure */
3372 	)
3373 {
3374 	if (cinf->pkey != NULL)
3375 		EVP_PKEY_free(cinf->pkey);
3376 	if (cinf->subject != NULL)
3377 		free(cinf->subject);
3378 	if (cinf->issuer != NULL)
3379 		free(cinf->issuer);
3380 	if (cinf->grpkey != NULL)
3381 		free(cinf->grpkey);
3382 	value_free(&cinf->cert);
3383 	free(cinf);
3384 }
3385 
3386 
3387 /*
3388  ***********************************************************************
3389  *								       *
3390  * The following routines are used only at initialization time         *
3391  *								       *
3392  ***********************************************************************
3393  */
3394 /*
3395  * crypto_key - load cryptographic parameters and keys from files
3396  *
3397  * This routine loads a PEM-encoded public/private key pair and extracts
3398  * the filestamp from the file name.
3399  *
3400  * Returns public key pointer if valid, NULL if not. Side effect updates
3401  * the filestamp if valid.
3402  */
3403 static EVP_PKEY *
3404 crypto_key(
3405 	char	*cp,		/* file name */
3406 	tstamp_t *fstamp	/* filestamp */
3407 	)
3408 {
3409 	FILE	*str;		/* file handle */
3410 	EVP_PKEY *pkey = NULL;	/* public/private key */
3411 	char	filename[MAXFILENAME]; /* name of key file */
3412 	char	linkname[MAXFILENAME]; /* filestamp buffer) */
3413 	char	statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3414 	char	*ptr;
3415 
3416 	/*
3417 	 * Open the key file. If the first character of the file name is
3418 	 * not '/', prepend the keys directory string. If something goes
3419 	 * wrong, abandon ship.
3420 	 */
3421 	if (*cp == '/')
3422 		strcpy(filename, cp);
3423 	else
3424 		snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
3425 	str = fopen(filename, "r");
3426 	if (str == NULL)
3427 		return (NULL);
3428 
3429 	/*
3430 	 * Read the filestamp, which is contained in the first line.
3431 	 */
3432 	if ((ptr = fgets(linkname, MAXFILENAME, str)) == NULL) {
3433 		msyslog(LOG_ERR, "crypto_key: no data %s\n",
3434 		    filename);
3435 		return (NULL);
3436 	}
3437 	if ((ptr = strrchr(ptr, '.')) == NULL) {
3438 		msyslog(LOG_ERR, "crypto_key: no filestamp %s\n",
3439 		    filename);
3440 		return (NULL);
3441 	}
3442 	if (sscanf(++ptr, "%u", fstamp) != 1) {
3443 		msyslog(LOG_ERR, "crypto_key: invalid timestamp %s\n",
3444 		    filename);
3445 		return (NULL);
3446 	}
3447 
3448 	/*
3449 	 * Read and decrypt PEM-encoded private key.
3450 	 */
3451 	pkey = PEM_read_PrivateKey(str, NULL, NULL, passwd);
3452 	fclose(str);
3453 	if (pkey == NULL) {
3454 		msyslog(LOG_ERR, "crypto_key %s\n",
3455 		    ERR_error_string(ERR_get_error(), NULL));
3456 		return (NULL);
3457 	}
3458 
3459 	/*
3460 	 * Leave tracks in the cryptostats.
3461 	 */
3462 	if ((ptr = strrchr(linkname, '\n')) != NULL)
3463 		*ptr = '\0';
3464 	sprintf(statstr, "%s mod %d", &linkname[2],
3465 	    EVP_PKEY_size(pkey) * 8);
3466 	record_crypto_stats(NULL, statstr);
3467 #ifdef DEBUG
3468 	if (debug)
3469 		printf("crypto_key: %s\n", statstr);
3470 	if (debug > 1) {
3471 		if (EVP_MD_type(pkey) == EVP_PKEY_DSA)
3472 			DSA_print_fp(stdout, pkey->pkey.dsa, 0);
3473 		else
3474 			RSA_print_fp(stdout, pkey->pkey.rsa, 0);
3475 	}
3476 #endif
3477 	return (pkey);
3478 }
3479 
3480 
3481 /*
3482  * crypto_cert - load certificate from file
3483  *
3484  * This routine loads a X.509 RSA or DSA certificate from a file and
3485  * constructs a info/cert value structure for this machine. The
3486  * structure includes a filestamp extracted from the file name. Later
3487  * the certificate can be sent to another machine by request.
3488  *
3489  * Returns certificate info/value pointer if valid, NULL if not.
3490  */
3491 static struct cert_info *	/* certificate information */
3492 crypto_cert(
3493 	char	*cp		/* file name */
3494 	)
3495 {
3496 	struct cert_info *ret; /* certificate information */
3497 	FILE	*str;		/* file handle */
3498 	char	filename[MAXFILENAME]; /* name of certificate file */
3499 	char	linkname[MAXFILENAME]; /* filestamp buffer */
3500 	char	statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3501 	tstamp_t fstamp;	/* filestamp */
3502 	long	len;
3503 	char	*ptr;
3504 	char	*name, *header;
3505 	u_char	*data;
3506 
3507 	/*
3508 	 * Open the certificate file. If the first character of the file
3509 	 * name is not '/', prepend the keys directory string. If
3510 	 * something goes wrong, abandon ship.
3511 	 */
3512 	if (*cp == '/')
3513 		strcpy(filename, cp);
3514 	else
3515 		snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
3516 	str = fopen(filename, "r");
3517 	if (str == NULL)
3518 		return (NULL);
3519 
3520 	/*
3521 	 * Read the filestamp, which is contained in the first line.
3522 	 */
3523 	if ((ptr = fgets(linkname, MAXFILENAME, str)) == NULL) {
3524 		msyslog(LOG_ERR, "crypto_cert: no data %s\n",
3525 		    filename);
3526 		return (NULL);
3527 	}
3528 	if ((ptr = strrchr(ptr, '.')) == NULL) {
3529 		msyslog(LOG_ERR, "crypto_cert: no filestamp %s\n",
3530 		    filename);
3531 		return (NULL);
3532 	}
3533 	if (sscanf(++ptr, "%u", &fstamp) != 1) {
3534 		msyslog(LOG_ERR, "crypto_cert: invalid filestamp %s\n",
3535 		    filename);
3536 		return (NULL);
3537 	}
3538 
3539 	/*
3540 	 * Read PEM-encoded certificate and install.
3541 	 */
3542 	if (!PEM_read(str, &name, &header, &data, &len)) {
3543 		msyslog(LOG_ERR, "crypto_cert %s\n",
3544 		    ERR_error_string(ERR_get_error(), NULL));
3545 		return (NULL);
3546 	}
3547 	free(header);
3548 	if (strcmp(name, "CERTIFICATE") !=0) {
3549 		msyslog(LOG_INFO, "crypto_cert: wrong PEM type %s",
3550 		    name);
3551 		free(name);
3552 		free(data);
3553 		return (NULL);
3554 	}
3555 	free(name);
3556 
3557 	/*
3558 	 * Parse certificate and generate info/value structure.
3559 	 */
3560 	ret = cert_parse(data, len, fstamp);
3561 	free(data);
3562 	if (ret == NULL)
3563 		return (NULL);
3564 	if ((ptr = strrchr(linkname, '\n')) != NULL)
3565 		*ptr = '\0';
3566 	sprintf(statstr, "%s 0x%x len %lu", &linkname[2], ret->flags,
3567 	    len);
3568 	record_crypto_stats(NULL, statstr);
3569 #ifdef DEBUG
3570 	if (debug)
3571 		printf("crypto_cert: %s\n", statstr);
3572 #endif
3573 	return (ret);
3574 }
3575 
3576 
3577 /*
3578  * crypto_tai - load leapseconds table from file
3579  *
3580  * This routine loads the ERTS leapsecond file in NIST text format,
3581  * converts to a value structure and extracts a filestamp from the file
3582  * name. The data are used to establish the TAI offset from UTC, which
3583  * is provided to the kernel if supported. Later the data can be sent to
3584  * another machine on request.
3585  */
3586 static void
3587 crypto_tai(
3588 	char	*cp		/* file name */
3589 	)
3590 {
3591 	FILE	*str;		/* file handle */
3592 	char	buf[NTP_MAXSTRLEN];	/* file line buffer */
3593 	u_int	leapsec[MAX_LEAP]; /* NTP time at leaps */
3594 	u_int	offset;		/* offset at leap (s) */
3595 	char	filename[MAXFILENAME]; /* name of leapseconds file */
3596 	char	linkname[MAXFILENAME]; /* file link (for filestamp) */
3597 	char	statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3598 	tstamp_t fstamp;	/* filestamp */
3599 	u_int	len;
3600 	char	*ptr;
3601 	int	rval, i;
3602 #ifdef KERNEL_PLL
3603 #if NTP_API > 3
3604 	struct timex ntv;	/* kernel interface structure */
3605 #endif /* NTP_API */
3606 #endif /* KERNEL_PLL */
3607 
3608 	/*
3609 	 * Open the file and discard comment lines. If the first
3610 	 * character of the file name is not '/', prepend the keys
3611 	 * directory string. If the file is not found, not to worry; it
3612 	 * can be retrieved over the net. But, if it is found with
3613 	 * errors, we crash and burn.
3614 	 */
3615 	if (*cp == '/')
3616 		strcpy(filename, cp);
3617 	else
3618 		snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
3619 	if ((str = fopen(filename, "r")) == NULL)
3620 		return;
3621 
3622 	/*
3623 	 * Extract filestamp if present.
3624 	 */
3625 	rval = readlink(filename, linkname, MAXFILENAME - 1);
3626 	if (rval > 0) {
3627 		linkname[rval] = '\0';
3628 		ptr = strrchr(linkname, '.');
3629 	} else {
3630 		ptr = strrchr(filename, '.');
3631 	}
3632 	if (ptr != NULL)
3633 		sscanf(++ptr, "%u", &fstamp);
3634 	else
3635 		fstamp = 0;
3636 	tai_leap.fstamp = htonl(fstamp);
3637 
3638 	/*
3639 	 * We are rather paranoid here, since an intruder might cause a
3640 	 * coredump by infiltrating naughty values. Empty lines and
3641 	 * comments are ignored. Other lines must begin with two
3642 	 * integers followed by junk or comments. The first integer is
3643 	 * the NTP seconds of leap insertion, the second is the offset
3644 	 * of TAI relative to UTC after that insertion. The second word
3645 	 * must equal the initial insertion of ten seconds on 1 January
3646 	 * 1972 plus one second for each succeeding insertion.
3647 	 */
3648 	i = 0;
3649 	while (i < MAX_LEAP) {
3650 		ptr = fgets(buf, NTP_MAXSTRLEN - 1, str);
3651 		if (ptr == NULL)
3652 			break;
3653 		if (strlen(buf) < 1)
3654 			continue;
3655 		if (*buf == '#')
3656 			continue;
3657 		if (sscanf(buf, "%u %u", &leapsec[i], &offset) != 2)
3658 			continue;
3659 		if (i != (int)(offset - TAI_1972)) {
3660 			break;
3661 		}
3662 		i++;
3663 	}
3664 	fclose(str);
3665 	if (ptr != NULL) {
3666 		msyslog(LOG_INFO,
3667 		    "crypto_tai: leapseconds file %s error %d", cp,
3668 		    rval);
3669 		exit (-1);
3670 	}
3671 
3672 	/*
3673 	 * The extension field table entries consists of the NTP seconds
3674 	 * of leap insertion in reverse order, so that the most recent
3675 	 * insertion is the first entry in the table.
3676 	 */
3677 	len = i * 4;
3678 	tai_leap.vallen = htonl(len);
3679 	ptr = emalloc(len);
3680 	tai_leap.ptr = (unsigned char *) ptr;
3681 	for (; i >= 0; i--) {
3682 		*ptr++ = (char) htonl(leapsec[i]);
3683 	}
3684 	crypto_flags |= CRYPTO_FLAG_TAI;
3685 	sys_tai = len / 4 + TAI_1972 - 1;
3686 #ifdef KERNEL_PLL
3687 #if NTP_API > 3
3688 	ntv.modes = MOD_TAI;
3689 	ntv.constant = sys_tai;
3690 	if (ntp_adjtime(&ntv) == TIME_ERROR)
3691 		msyslog(LOG_INFO,
3692 		    "crypto_tai: kernel TAI update failed");
3693 #endif /* NTP_API */
3694 #endif /* KERNEL_PLL */
3695 	sprintf(statstr, "%s link %d fs %u offset %u", cp, rval, fstamp,
3696 	    ntohl(tai_leap.vallen) / 4 + TAI_1972 - 1);
3697 	record_crypto_stats(NULL, statstr);
3698 #ifdef DEBUG
3699 	if (debug)
3700 		printf("crypto_tai: %s\n", statstr);
3701 #endif
3702 }
3703 
3704 
3705 /*
3706  * crypto_setup - load keys, certificate and leapseconds table
3707  *
3708  * This routine loads the public/private host key and certificate. If
3709  * available, it loads the public/private sign key, which defaults to
3710  * the host key, and leapseconds table. The host key must be RSA, but
3711  * the sign key can be either RSA or DSA. In either case, the public key
3712  * on the certificate must agree with the sign key.
3713  */
3714 void
3715 crypto_setup(void)
3716 {
3717 	EVP_PKEY *pkey;		/* private/public key pair */
3718 	char	filename[MAXFILENAME]; /* file name buffer */
3719 	l_fp	seed;		/* crypto PRNG seed as NTP timestamp */
3720 	tstamp_t fstamp;	/* filestamp */
3721 	tstamp_t sstamp;	/* sign filestamp */
3722 	u_int	len, bytes;
3723 	u_char	*ptr;
3724 
3725 	/*
3726 	 * Initialize structures.
3727 	 */
3728 	if (!crypto_flags)
3729 		return;
3730 	gethostname(filename, MAXFILENAME);
3731 	bytes = strlen(filename) + 1;
3732 	sys_hostname = emalloc(bytes);
3733 	memcpy(sys_hostname, filename, bytes);
3734 	if (passwd == NULL)
3735 		passwd = sys_hostname;
3736 	memset(&hostval, 0, sizeof(hostval));
3737 	memset(&pubkey, 0, sizeof(pubkey));
3738 	memset(&tai_leap, 0, sizeof(tai_leap));
3739 
3740 	/*
3741 	 * Load required random seed file and seed the random number
3742 	 * generator. Be default, it is found in the user home
3743 	 * directory. The root home directory may be / or /root,
3744 	 * depending on the system. Wiggle the contents a bit and write
3745 	 * it back so the sequence does not repeat when we next restart.
3746 	 */
3747 	ERR_load_crypto_strings();
3748 	if (rand_file == NULL) {
3749 		if ((RAND_file_name(filename, MAXFILENAME)) != NULL) {
3750 			rand_file = emalloc(strlen(filename) + 1);
3751 			strcpy(rand_file, filename);
3752 		}
3753 	} else if (*rand_file != '/') {
3754 		snprintf(filename, MAXFILENAME, "%s/%s", keysdir,
3755 		    rand_file);
3756 		free(rand_file);
3757 		rand_file = emalloc(strlen(filename) + 1);
3758 		strcpy(rand_file, filename);
3759 	}
3760 	if (rand_file == NULL) {
3761 		msyslog(LOG_ERR,
3762 		    "crypto_setup: random seed file not specified");
3763 		exit (-1);
3764 	}
3765 	if ((bytes = RAND_load_file(rand_file, -1)) == 0) {
3766 		msyslog(LOG_ERR,
3767 		    "crypto_setup: random seed file %s not found\n",
3768 		    rand_file);
3769 		exit (-1);
3770 	}
3771 	get_systime(&seed);
3772 	RAND_seed(&seed, sizeof(l_fp));
3773 	RAND_write_file(rand_file);
3774 	OpenSSL_add_all_algorithms();
3775 #ifdef DEBUG
3776 	if (debug)
3777 		printf(
3778 		    "crypto_setup: OpenSSL version %lx random seed file %s bytes read %d\n",
3779 		    SSLeay(), rand_file, bytes);
3780 #endif
3781 
3782 	/*
3783 	 * Load required host key from file "ntpkey_host_<hostname>". It
3784 	 * also becomes the default sign key.
3785 	 */
3786 	if (host_file == NULL) {
3787 		snprintf(filename, MAXFILENAME, "ntpkey_host_%s",
3788 		    sys_hostname);
3789 		host_file = emalloc(strlen(filename) + 1);
3790 		strcpy(host_file, filename);
3791 	}
3792 	pkey = crypto_key(host_file, &fstamp);
3793 	if (pkey == NULL) {
3794 		msyslog(LOG_ERR,
3795 		    "crypto_setup: host key file %s not found or corrupt",
3796 		    host_file);
3797 		exit (-1);
3798 	}
3799 	host_pkey = pkey;
3800 	sign_pkey = pkey;
3801 	sstamp = fstamp;
3802 	hostval.fstamp = htonl(fstamp);
3803 	if (EVP_MD_type(host_pkey) != EVP_PKEY_RSA) {
3804 		msyslog(LOG_ERR,
3805 		    "crypto_setup: host key is not RSA key type");
3806 		exit (-1);
3807 	}
3808 	hostval.vallen = htonl(strlen(sys_hostname));
3809 	hostval.ptr = (unsigned char *) sys_hostname;
3810 
3811 	/*
3812 	 * Construct public key extension field for agreement scheme.
3813 	 */
3814 	len = i2d_PublicKey(host_pkey, NULL);
3815 	ptr = emalloc(len);
3816 	pubkey.ptr = ptr;
3817 	i2d_PublicKey(host_pkey, &ptr);
3818 	pubkey.vallen = htonl(len);
3819 	pubkey.fstamp = hostval.fstamp;
3820 
3821 	/*
3822 	 * Load optional sign key from file "ntpkey_sign_<hostname>". If
3823 	 * loaded, it becomes the sign key.
3824 	 */
3825 	if (sign_file == NULL) {
3826 		snprintf(filename, MAXFILENAME, "ntpkey_sign_%s",
3827 		    sys_hostname);
3828 		sign_file = emalloc(strlen(filename) + 1);
3829 		strcpy(sign_file, filename);
3830 	}
3831 	pkey = crypto_key(sign_file, &fstamp);
3832 	if (pkey != NULL) {
3833 		sign_pkey = pkey;
3834 		sstamp = fstamp;
3835 	}
3836 	sign_siglen = EVP_PKEY_size(sign_pkey);
3837 
3838 	/*
3839 	 * Load optional IFF parameters from file
3840 	 * "ntpkey_iff_<hostname>".
3841 	 */
3842 	if (iffpar_file == NULL) {
3843 		snprintf(filename, MAXFILENAME, "ntpkey_iff_%s",
3844 		    sys_hostname);
3845 		iffpar_file = emalloc(strlen(filename) + 1);
3846 		strcpy(iffpar_file, filename);
3847 	}
3848 	iffpar_pkey = crypto_key(iffpar_file, &if_fstamp);
3849 	if (iffpar_pkey != NULL)
3850 		crypto_flags |= CRYPTO_FLAG_IFF;
3851 
3852 	/*
3853 	 * Load optional GQ parameters from file "ntpkey_gq_<hostname>".
3854 	 */
3855 	if (gqpar_file == NULL) {
3856 		snprintf(filename, MAXFILENAME, "ntpkey_gq_%s",
3857 		    sys_hostname);
3858 		gqpar_file = emalloc(strlen(filename) + 1);
3859 		strcpy(gqpar_file, filename);
3860 	}
3861 	gqpar_pkey = crypto_key(gqpar_file, &gq_fstamp);
3862 	if (gqpar_pkey != NULL)
3863 		crypto_flags |= CRYPTO_FLAG_GQ;
3864 
3865 	/*
3866 	 * Load optional MV parameters from file "ntpkey_mv_<hostname>".
3867 	 */
3868 	if (mvpar_file == NULL) {
3869 		snprintf(filename, MAXFILENAME, "ntpkey_mv_%s",
3870 		    sys_hostname);
3871 		mvpar_file = emalloc(strlen(filename) + 1);
3872 		strcpy(mvpar_file, filename);
3873 	}
3874 	mvpar_pkey = crypto_key(mvpar_file, &mv_fstamp);
3875 	if (mvpar_pkey != NULL)
3876 		crypto_flags |= CRYPTO_FLAG_MV;
3877 
3878 	/*
3879 	 * Load required certificate from file "ntpkey_cert_<hostname>".
3880 	 */
3881 	if (cert_file == NULL) {
3882 		snprintf(filename, MAXFILENAME, "ntpkey_cert_%s",
3883 		    sys_hostname);
3884 		cert_file = emalloc(strlen(filename) + 1);
3885 		strcpy(cert_file, filename);
3886 	}
3887 	if ((cinfo = crypto_cert(cert_file)) == NULL) {
3888 		msyslog(LOG_ERR,
3889 		    "certificate file %s not found or corrupt",
3890 		    cert_file);
3891 		exit (-1);
3892 	}
3893 
3894 	/*
3895 	 * The subject name must be the same as the host name, unless
3896 	 * the certificate is private, in which case it may have come
3897 	 * from another host.
3898 	 */
3899 	if (!(cinfo->flags & CERT_PRIV) && strcmp(cinfo->subject,
3900 	    sys_hostname) != 0) {
3901 		msyslog(LOG_ERR,
3902 		    "crypto_setup: certificate %s not for this host",
3903 		    cert_file);
3904 		cert_free(cinfo);
3905 		exit (-1);
3906 	}
3907 
3908 	/*
3909 	 * It the certificate is trusted, the subject must be the same
3910 	 * as the issuer, in other words it must be self signed.
3911 	 */
3912 	if (cinfo->flags & CERT_PRIV && strcmp(cinfo->subject,
3913 	    cinfo->issuer) != 0) {
3914 		if (cert_valid(cinfo, sign_pkey) != XEVNT_OK) {
3915 			msyslog(LOG_ERR,
3916 			    "crypto_setup: certificate %s is trusted, but not self signed.",
3917 			    cert_file);
3918 			cert_free(cinfo);
3919 			exit (-1);
3920 		}
3921 	}
3922 	sign_digest = cinfo->digest;
3923 	if (cinfo->flags & CERT_PRIV)
3924 		crypto_flags |= CRYPTO_FLAG_PRIV;
3925 	crypto_flags |= cinfo->nid << 16;
3926 
3927 	/*
3928 	 * Load optional leapseconds table from file "ntpkey_leap". If
3929 	 * the file is missing or defective, the values can later be
3930 	 * retrieved from a server.
3931 	 */
3932 	if (leap_file == NULL)
3933 		leap_file = "ntpkey_leap";
3934 	crypto_tai(leap_file);
3935 #ifdef DEBUG
3936 	if (debug)
3937 		printf(
3938 		    "crypto_setup: flags 0x%x host %s signature %s\n",
3939 		    crypto_flags, sys_hostname, OBJ_nid2ln(cinfo->nid));
3940 #endif
3941 }
3942 
3943 
3944 /*
3945  * crypto_config - configure data from crypto configuration command.
3946  */
3947 void
3948 crypto_config(
3949 	int	item,		/* configuration item */
3950 	char	*cp		/* file name */
3951 	)
3952 {
3953 	switch (item) {
3954 
3955 	/*
3956 	 * Set random seed file name.
3957 	 */
3958 	case CRYPTO_CONF_RAND:
3959 		rand_file = emalloc(strlen(cp) + 1);
3960 		strcpy(rand_file, cp);
3961 		break;
3962 
3963 	/*
3964 	 * Set private key password.
3965 	 */
3966 	case CRYPTO_CONF_PW:
3967 		passwd = emalloc(strlen(cp) + 1);
3968 		strcpy(passwd, cp);
3969 		break;
3970 
3971 	/*
3972 	 * Set host file name.
3973 	 */
3974 	case CRYPTO_CONF_PRIV:
3975 		host_file = emalloc(strlen(cp) + 1);
3976 		strcpy(host_file, cp);
3977 		break;
3978 
3979 	/*
3980 	 * Set sign key file name.
3981 	 */
3982 	case CRYPTO_CONF_SIGN:
3983 		sign_file = emalloc(strlen(cp) + 1);
3984 		strcpy(sign_file, cp);
3985 		break;
3986 
3987 	/*
3988 	 * Set iff parameters file name.
3989 	 */
3990 	case CRYPTO_CONF_IFFPAR:
3991 		iffpar_file = emalloc(strlen(cp) + 1);
3992 		strcpy(iffpar_file, cp);
3993 		break;
3994 
3995 	/*
3996 	 * Set gq parameters file name.
3997 	 */
3998 	case CRYPTO_CONF_GQPAR:
3999 		gqpar_file = emalloc(strlen(cp) + 1);
4000 		strcpy(gqpar_file, cp);
4001 		break;
4002 
4003 	/*
4004 	 * Set mv parameters file name.
4005 	 */
4006 	case CRYPTO_CONF_MVPAR:
4007 		mvpar_file = emalloc(strlen(cp) + 1);
4008 		strcpy(mvpar_file, cp);
4009 		break;
4010 
4011 	/*
4012 	 * Set certificate file name.
4013 	 */
4014 	case CRYPTO_CONF_CERT:
4015 		cert_file = emalloc(strlen(cp) + 1);
4016 		strcpy(cert_file, cp);
4017 		break;
4018 
4019 	/*
4020 	 * Set leapseconds file name.
4021 	 */
4022 	case CRYPTO_CONF_LEAP:
4023 		leap_file = emalloc(strlen(cp) + 1);
4024 		strcpy(leap_file, cp);
4025 		break;
4026 	}
4027 	crypto_flags |= CRYPTO_FLAG_ENAB;
4028 }
4029 # else
4030 int ntp_crypto_bs_pubkey;
4031 # endif /* OPENSSL */
4032