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