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