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