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