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