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