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