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