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