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