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