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