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