ntp_crypto.c revision 294904
182498Sroberto/*
282498Sroberto * ntp_crypto.c - NTP version 4 public key routines
382498Sroberto */
482498Sroberto#ifdef HAVE_CONFIG_H
582498Sroberto#include <config.h>
682498Sroberto#endif
782498Sroberto
8285612Sdelphij#ifdef AUTOKEY
982498Sroberto#include <stdio.h>
10285612Sdelphij#include <stdlib.h>	/* strtoul */
1182498Sroberto#include <sys/types.h>
12132451Sroberto#include <sys/param.h>
1382498Sroberto#include <unistd.h>
1482498Sroberto#include <fcntl.h>
1582498Sroberto
1682498Sroberto#include "ntpd.h"
1782498Sroberto#include "ntp_stdlib.h"
18132451Sroberto#include "ntp_unixtime.h"
1982498Sroberto#include "ntp_string.h"
20285612Sdelphij#include "ntp_random.h"
21285612Sdelphij#include "ntp_assert.h"
22285612Sdelphij#include "ntp_calendar.h"
23285612Sdelphij#include "ntp_leapsec.h"
2482498Sroberto
25132451Sroberto#include "openssl/asn1_mac.h"
26132451Sroberto#include "openssl/bn.h"
27132451Sroberto#include "openssl/err.h"
28132451Sroberto#include "openssl/evp.h"
29132451Sroberto#include "openssl/pem.h"
30132451Sroberto#include "openssl/rand.h"
31132451Sroberto#include "openssl/x509v3.h"
32132451Sroberto
3382498Sroberto#ifdef KERNEL_PLL
3482498Sroberto#include "ntp_syscall.h"
3582498Sroberto#endif /* KERNEL_PLL */
3682498Sroberto
3782498Sroberto/*
38285612Sdelphij * calcomp - compare two calendar structures, ignoring yearday and weekday; like strcmp
39285612Sdelphij * No, it's not a plotter.  If you don't understand that, you're too young.
40285612Sdelphij */
41285612Sdelphijstatic int calcomp(struct calendar *pjd1, struct calendar *pjd2)
42285612Sdelphij{
43285612Sdelphij	int32_t diff;	/* large enough to hold the signed difference between two uint16_t values */
44285612Sdelphij
45285612Sdelphij	diff = pjd1->year - pjd2->year;
46285612Sdelphij	if (diff < 0) return -1; else if (diff > 0) return 1;
47285612Sdelphij	/* same year; compare months */
48285612Sdelphij	diff = pjd1->month - pjd2->month;
49285612Sdelphij	if (diff < 0) return -1; else if (diff > 0) return 1;
50285612Sdelphij	/* same year and month; compare monthday */
51285612Sdelphij	diff = pjd1->monthday - pjd2->monthday;
52285612Sdelphij	if (diff < 0) return -1; else if (diff > 0) return 1;
53285612Sdelphij	/* same year and month and monthday; compare time */
54285612Sdelphij	diff = pjd1->hour - pjd2->hour;
55285612Sdelphij	if (diff < 0) return -1; else if (diff > 0) return 1;
56285612Sdelphij	diff = pjd1->minute - pjd2->minute;
57285612Sdelphij	if (diff < 0) return -1; else if (diff > 0) return 1;
58285612Sdelphij	diff = pjd1->second - pjd2->second;
59285612Sdelphij	if (diff < 0) return -1; else if (diff > 0) return 1;
60285612Sdelphij	/* identical */
61285612Sdelphij	return 0;
62285612Sdelphij}
63285612Sdelphij
64285612Sdelphij/*
65132451Sroberto * Extension field message format
6682498Sroberto *
67132451Sroberto * These are always signed and saved before sending in network byte
68132451Sroberto * order. They must be converted to and from host byte order for
69132451Sroberto * processing.
7082498Sroberto *
71132451Sroberto * +-------+-------+
72132451Sroberto * |   op  |  len  | <- extension pointer
73132451Sroberto * +-------+-------+
74285612Sdelphij * |    associd    |
75132451Sroberto * +---------------+
76132451Sroberto * |   timestamp   | <- value pointer
77132451Sroberto * +---------------+
78132451Sroberto * |   filestamp   |
79132451Sroberto * +---------------+
80132451Sroberto * |   value len   |
81132451Sroberto * +---------------+
82132451Sroberto * |               |
83132451Sroberto * =     value     =
84132451Sroberto * |               |
85132451Sroberto * +---------------+
86132451Sroberto * | signature len |
87132451Sroberto * +---------------+
88132451Sroberto * |               |
89132451Sroberto * =   signature   =
90132451Sroberto * |               |
91132451Sroberto * +---------------+
9282498Sroberto *
93132451Sroberto * The CRYPTO_RESP bit is set to 0 for requests, 1 for responses.
94132451Sroberto * Requests carry the association ID of the receiver; responses carry
95132451Sroberto * the association ID of the sender. Some messages include only the
96132451Sroberto * operation/length and association ID words and so have length 8
97132451Sroberto * octets. Ohers include the value structure and associated value and
98132451Sroberto * signature fields. These messages include the timestamp, filestamp,
99132451Sroberto * value and signature words and so have length at least 24 octets. The
100132451Sroberto * signature and/or value fields can be empty, in which case the
101132451Sroberto * respective length words are zero. An empty value with nonempty
102132451Sroberto * signature is syntactically valid, but semantically questionable.
103132451Sroberto *
104132451Sroberto * The filestamp represents the time when a cryptographic data file such
105132451Sroberto * as a public/private key pair is created. It follows every reference
106132451Sroberto * depending on that file and serves as a means to obsolete earlier data
107132451Sroberto * of the same type. The timestamp represents the time when the
108132451Sroberto * cryptographic data of the message were last signed. Creation of a
109132451Sroberto * cryptographic data file or signing a message can occur only when the
110132451Sroberto * creator or signor is synchronized to an authoritative source and
111132451Sroberto * proventicated to a trusted authority.
112132451Sroberto *
113285612Sdelphij * Note there are several conditions required for server trust. First,
114285612Sdelphij * the public key on the server certificate must be verified, which can
115285612Sdelphij * involve a hike along the certificate trail to a trusted host. Next,
116285612Sdelphij * the server trust must be confirmed by one of several identity
117285612Sdelphij * schemes. Valid cryptographic values are signed with attached
118285612Sdelphij * timestamp and filestamp. Individual packet trust is confirmed
119285612Sdelphij * relative to these values by a message digest with keys generated by a
120285612Sdelphij * reverse-order pseudorandom hash.
121285612Sdelphij *
122285612Sdelphij * State decomposition. These flags are lit in the order given. They are
123285612Sdelphij * dim only when the association is demobilized.
124285612Sdelphij *
125285612Sdelphij * CRYPTO_FLAG_ENAB	Lit upon acceptance of a CRYPTO_ASSOC message
126285612Sdelphij * CRYPTO_FLAG_CERT	Lit when a self-digned trusted certificate is
127285612Sdelphij *			accepted.
128285612Sdelphij * CRYPTO_FLAG_VRFY	Lit when identity is confirmed.
129285612Sdelphij * CRYPTO_FLAG_PROV	Lit when the first signature is verified.
130285612Sdelphij * CRYPTO_FLAG_COOK	Lit when a valid cookie is accepted.
131285612Sdelphij * CRYPTO_FLAG_AUTO	Lit when valid autokey values are accepted.
132285612Sdelphij * CRYPTO_FLAG_SIGN	Lit when the server signed certificate is
133285612Sdelphij *			accepted.
134285612Sdelphij * CRYPTO_FLAG_LEAP	Lit when the leapsecond values are accepted.
13582498Sroberto */
13682498Sroberto/*
137132451Sroberto * Cryptodefines
13882498Sroberto */
139132451Sroberto#define TAI_1972	10	/* initial TAI offset (s) */
140132451Sroberto#define MAX_LEAP	100	/* max UTC leapseconds (s) */
141132451Sroberto#define VALUE_LEN	(6 * 4) /* min response field length */
142281230Sdelphij#define MAX_VALLEN	(65535 - VALUE_LEN)
143132451Sroberto#define YEAR		(60 * 60 * 24 * 365) /* seconds in year */
14482498Sroberto
14582498Sroberto/*
146132451Sroberto * Global cryptodata in host byte order
14782498Sroberto */
148132451Srobertou_int32	crypto_flags = 0x0;	/* status word */
149285612Sdelphijint	crypto_nid = KEY_TYPE_MD5; /* digest nid */
150285612Sdelphijchar	*sys_hostname = NULL;
151285612Sdelphijchar	*sys_groupname = NULL;
152285612Sdelphijstatic char *host_filename = NULL;	/* host file name */
153285612Sdelphijstatic char *ident_filename = NULL;	/* group file name */
15482498Sroberto
15582498Sroberto/*
156132451Sroberto * Global cryptodata in network byte order
15782498Sroberto */
158285612Sdelphijstruct cert_info *cinfo = NULL;	/* certificate info/value cache */
159285612Sdelphijstruct cert_info *cert_host = NULL; /* host certificate */
160285612Sdelphijstruct pkey_info *pkinfo = NULL; /* key info/value cache */
161132451Srobertostruct value hostval;		/* host value */
162132451Srobertostruct value pubkey;		/* public key */
163285612Sdelphijstruct value tai_leap;		/* leapseconds values */
164285612Sdelphijstruct pkey_info *iffkey_info = NULL; /* IFF keys */
165285612Sdelphijstruct pkey_info *gqkey_info = NULL; /* GQ keys */
166285612Sdelphijstruct pkey_info *mvkey_info = NULL; /* MV keys */
16782498Sroberto
16882498Sroberto/*
169132451Sroberto * Private cryptodata in host byte order
17082498Sroberto */
171132451Srobertostatic char *passwd = NULL;	/* private key password */
172132451Srobertostatic EVP_PKEY *host_pkey = NULL; /* host key */
173132451Srobertostatic EVP_PKEY *sign_pkey = NULL; /* sign key */
174132451Srobertostatic const EVP_MD *sign_digest = NULL; /* sign digest */
175132451Srobertostatic u_int sign_siglen;	/* sign key length */
176132451Srobertostatic char *rand_file = NULL;	/* random seed file */
17782498Sroberto
17882498Sroberto/*
17982498Sroberto * Cryptotypes
18082498Sroberto */
181285612Sdelphijstatic	int	crypto_verify	(struct exten *, struct value *,
182285612Sdelphij				    struct peer *);
183285612Sdelphijstatic	int	crypto_encrypt	(const u_char *, u_int, keyid_t *,
184285612Sdelphij				    struct value *);
185285612Sdelphijstatic	int	crypto_alice	(struct peer *, struct value *);
186285612Sdelphijstatic	int	crypto_alice2	(struct peer *, struct value *);
187285612Sdelphijstatic	int	crypto_alice3	(struct peer *, struct value *);
188285612Sdelphijstatic	int	crypto_bob	(struct exten *, struct value *);
189285612Sdelphijstatic	int	crypto_bob2	(struct exten *, struct value *);
190285612Sdelphijstatic	int	crypto_bob3	(struct exten *, struct value *);
191285612Sdelphijstatic	int	crypto_iff	(struct exten *, struct peer *);
192285612Sdelphijstatic	int	crypto_gq	(struct exten *, struct peer *);
193285612Sdelphijstatic	int	crypto_mv	(struct exten *, struct peer *);
194285612Sdelphijstatic	int	crypto_send	(struct exten *, struct value *, int);
195285612Sdelphijstatic	tstamp_t crypto_time	(void);
196285612Sdelphijstatic	void	asn_to_calendar		(ASN1_TIME *, struct calendar*);
197285612Sdelphijstatic	struct cert_info *cert_parse (const u_char *, long, tstamp_t);
198285612Sdelphijstatic	int	cert_sign	(struct exten *, struct value *);
199285612Sdelphijstatic	struct cert_info *cert_install (struct exten *, struct peer *);
200285612Sdelphijstatic	int	cert_hike	(struct peer *, struct cert_info *);
201285612Sdelphijstatic	void	cert_free	(struct cert_info *);
202285612Sdelphijstatic	struct pkey_info *crypto_key (char *, char *, sockaddr_u *);
203285612Sdelphijstatic	void	bighash		(BIGNUM *, BIGNUM *);
204285612Sdelphijstatic	struct cert_info *crypto_cert (char *);
205289999Sglebiusstatic	u_int	exten_payload_size(const struct exten *);
20682498Sroberto
207132451Sroberto#ifdef SYS_WINNT
208132451Srobertoint
209132451Srobertoreadlink(char * link, char * file, int len) {
210132451Sroberto	return (-1);
211132451Sroberto}
212132451Sroberto#endif
21382498Sroberto
21482498Sroberto/*
21582498Sroberto * session_key - generate session key
21682498Sroberto *
21782498Sroberto * This routine generates a session key from the source address,
21882498Sroberto * destination address, key ID and private value. The value of the
21982498Sroberto * session key is the MD5 hash of these values, while the next key ID is
22082498Sroberto * the first four octets of the hash.
221132451Sroberto *
222285612Sdelphij * Returns the next key ID or 0 if there is no destination address.
22382498Sroberto */
224132451Srobertokeyid_t
22582498Srobertosession_key(
226285612Sdelphij	sockaddr_u *srcadr, 	/* source address */
227285612Sdelphij	sockaddr_u *dstadr, 	/* destination address */
228132451Sroberto	keyid_t	keyno,		/* key ID */
229132451Sroberto	keyid_t	private,	/* private value */
230132451Sroberto	u_long	lifetime 	/* key lifetime */
23182498Sroberto	)
23282498Sroberto{
233132451Sroberto	EVP_MD_CTX ctx;		/* message digest context */
234132451Sroberto	u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
235132451Sroberto	keyid_t	keyid;		/* key identifer */
236132451Sroberto	u_int32	header[10];	/* data in network byte order */
237132451Sroberto	u_int	hdlen, len;
23882498Sroberto
239182007Sroberto	if (!dstadr)
240182007Sroberto		return 0;
241182007Sroberto
24282498Sroberto	/*
24382498Sroberto	 * Generate the session key and key ID. If the lifetime is
24482498Sroberto	 * greater than zero, install the key and call it trusted.
24582498Sroberto	 */
246132451Sroberto	hdlen = 0;
247285612Sdelphij	switch(AF(srcadr)) {
248132451Sroberto	case AF_INET:
249285612Sdelphij		header[0] = NSRCADR(srcadr);
250285612Sdelphij		header[1] = NSRCADR(dstadr);
251132451Sroberto		header[2] = htonl(keyno);
252132451Sroberto		header[3] = htonl(private);
253132451Sroberto		hdlen = 4 * sizeof(u_int32);
254132451Sroberto		break;
255182007Sroberto
256132451Sroberto	case AF_INET6:
257285612Sdelphij		memcpy(&header[0], PSOCK_ADDR6(srcadr),
258132451Sroberto		    sizeof(struct in6_addr));
259285612Sdelphij		memcpy(&header[4], PSOCK_ADDR6(dstadr),
260132451Sroberto		    sizeof(struct in6_addr));
261132451Sroberto		header[8] = htonl(keyno);
262132451Sroberto		header[9] = htonl(private);
263132451Sroberto		hdlen = 10 * sizeof(u_int32);
264132451Sroberto		break;
265132451Sroberto	}
266285612Sdelphij	EVP_DigestInit(&ctx, EVP_get_digestbynid(crypto_nid));
267132451Sroberto	EVP_DigestUpdate(&ctx, (u_char *)header, hdlen);
268132451Sroberto	EVP_DigestFinal(&ctx, dgst, &len);
269132451Sroberto	memcpy(&keyid, dgst, 4);
27082498Sroberto	keyid = ntohl(keyid);
27182498Sroberto	if (lifetime != 0) {
272294904Sdelphij		MD5auth_setkey(keyno, crypto_nid, dgst, len, NULL);
27382498Sroberto		authtrust(keyno, lifetime);
27482498Sroberto	}
275285612Sdelphij	DPRINTF(2, ("session_key: %s > %s %08x %08x hash %08x life %lu\n",
276132451Sroberto		    stoa(srcadr), stoa(dstadr), keyno,
277285612Sdelphij		    private, keyid, lifetime));
278285612Sdelphij
27982498Sroberto	return (keyid);
28082498Sroberto}
28182498Sroberto
28282498Sroberto
28382498Sroberto/*
28482498Sroberto * make_keylist - generate key list
28582498Sroberto *
286182007Sroberto * Returns
287182007Sroberto * XEVNT_OK	success
288285612Sdelphij * XEVNT_ERR	protocol error
289182007Sroberto *
29082498Sroberto * This routine constructs a pseudo-random sequence by repeatedly
29182498Sroberto * hashing the session key starting from a given source address,
29282498Sroberto * destination address, private value and the next key ID of the
29382498Sroberto * preceeding session key. The last entry on the list is saved along
29482498Sroberto * with its sequence number and public signature.
29582498Sroberto */
296182007Srobertoint
29782498Srobertomake_keylist(
29882498Sroberto	struct peer *peer,	/* peer structure pointer */
29982498Sroberto	struct interface *dstadr /* interface */
30082498Sroberto	)
30182498Sroberto{
302132451Sroberto	EVP_MD_CTX ctx;		/* signature context */
303132451Sroberto	tstamp_t tstamp;	/* NTP timestamp */
30482498Sroberto	struct autokey *ap;	/* autokey pointer */
305132451Sroberto	struct value *vp;	/* value pointer */
306132451Sroberto	keyid_t	keyid = 0;	/* next key ID */
307132451Sroberto	keyid_t	cookie;		/* private value */
308285612Sdelphij	long	lifetime;
309182007Sroberto	u_int	len, mpoll;
310132451Sroberto	int	i;
31182498Sroberto
312182007Sroberto	if (!dstadr)
313285612Sdelphij		return XEVNT_ERR;
314182007Sroberto
31582498Sroberto	/*
31682498Sroberto	 * Allocate the key list if necessary.
31782498Sroberto	 */
318132451Sroberto	tstamp = crypto_time();
31982498Sroberto	if (peer->keylist == NULL)
320285612Sdelphij		peer->keylist = eallocarray(NTP_MAXSESSION,
321285612Sdelphij					    sizeof(keyid_t));
32282498Sroberto
32382498Sroberto	/*
32482498Sroberto	 * Generate an initial key ID which is unique and greater than
32582498Sroberto	 * NTP_MAXKEY.
32682498Sroberto	 */
32782498Sroberto	while (1) {
328285612Sdelphij		keyid = ntp_random() & 0xffffffff;
329285612Sdelphij		if (keyid <= NTP_MAXKEY)
330285612Sdelphij			continue;
331285612Sdelphij
33282498Sroberto		if (authhavekey(keyid))
33382498Sroberto			continue;
33482498Sroberto		break;
33582498Sroberto	}
33682498Sroberto
33782498Sroberto	/*
33882498Sroberto	 * Generate up to NTP_MAXSESSION session keys. Stop if the
33982498Sroberto	 * next one would not be unique or not a session key ID or if
34082498Sroberto	 * it would expire before the next poll. The private value
34182498Sroberto	 * included in the hash is zero if broadcast mode, the peer
34282498Sroberto	 * cookie if client mode or the host cookie if symmetric modes.
34382498Sroberto	 */
344182007Sroberto	mpoll = 1 << min(peer->ppoll, peer->hpoll);
345285612Sdelphij	lifetime = min(1U << sys_automax, NTP_MAXSESSION * mpoll);
34682498Sroberto	if (peer->hmode == MODE_BROADCAST)
34782498Sroberto		cookie = 0;
34882498Sroberto	else
349132451Sroberto		cookie = peer->pcookie;
35082498Sroberto	for (i = 0; i < NTP_MAXSESSION; i++) {
35182498Sroberto		peer->keylist[i] = keyid;
35282498Sroberto		peer->keynumber = i;
35382498Sroberto		keyid = session_key(&dstadr->sin, &peer->srcadr, keyid,
354285612Sdelphij		    cookie, lifetime + mpoll);
355182007Sroberto		lifetime -= mpoll;
35682498Sroberto		if (auth_havekey(keyid) || keyid <= NTP_MAXKEY ||
357285612Sdelphij		    lifetime < 0 || tstamp == 0)
35882498Sroberto			break;
35982498Sroberto	}
36082498Sroberto
36182498Sroberto	/*
36282498Sroberto	 * Save the last session key ID, sequence number and timestamp,
36382498Sroberto	 * then sign these values for later retrieval by the clients. Be
364132451Sroberto	 * careful not to use invalid key media. Use the public values
365132451Sroberto	 * timestamp as filestamp.
36682498Sroberto	 */
367132451Sroberto	vp = &peer->sndval;
368132451Sroberto	if (vp->ptr == NULL)
369132451Sroberto		vp->ptr = emalloc(sizeof(struct autokey));
370132451Sroberto	ap = (struct autokey *)vp->ptr;
37182498Sroberto	ap->seq = htonl(peer->keynumber);
37282498Sroberto	ap->key = htonl(keyid);
373132451Sroberto	vp->tstamp = htonl(tstamp);
374132451Sroberto	vp->fstamp = hostval.tstamp;
375132451Sroberto	vp->vallen = htonl(sizeof(struct autokey));
376132451Sroberto	vp->siglen = 0;
377182007Sroberto	if (tstamp != 0) {
378132451Sroberto		if (vp->sig == NULL)
379132451Sroberto			vp->sig = emalloc(sign_siglen);
380132451Sroberto		EVP_SignInit(&ctx, sign_digest);
381132451Sroberto		EVP_SignUpdate(&ctx, (u_char *)vp, 12);
382132451Sroberto		EVP_SignUpdate(&ctx, vp->ptr, sizeof(struct autokey));
383285612Sdelphij		if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
384289999Sglebius			INSIST(len <= sign_siglen);
385132451Sroberto			vp->siglen = htonl(len);
386285612Sdelphij			peer->flags |= FLAG_ASSOC;
387285612Sdelphij		}
388132451Sroberto	}
389285612Sdelphij	DPRINTF(1, ("make_keys: %d %08x %08x ts %u fs %u poll %d\n",
390285612Sdelphij		    peer->keynumber, keyid, cookie, ntohl(vp->tstamp),
391285612Sdelphij		    ntohl(vp->fstamp), peer->hpoll));
392182007Sroberto	return (XEVNT_OK);
39382498Sroberto}
39482498Sroberto
39582498Sroberto
39682498Sroberto/*
39782498Sroberto * crypto_recv - parse extension fields
39882498Sroberto *
39982498Sroberto * This routine is called when the packet has been matched to an
40082498Sroberto * association and passed sanity, format and MAC checks. We believe the
40182498Sroberto * extension field values only if the field has proper format and
40282498Sroberto * length, the timestamp and filestamp are valid and the signature has
40382498Sroberto * valid length and is verified. There are a few cases where some values
404132451Sroberto * are believed even if the signature fails, but only if the proventic
40582498Sroberto * bit is not set.
406285612Sdelphij *
407285612Sdelphij * Returns
408285612Sdelphij * XEVNT_OK	success
409285612Sdelphij * XEVNT_ERR	protocol error
410285612Sdelphij * XEVNT_LEN	bad field format or length
41182498Sroberto */
412132451Srobertoint
41382498Srobertocrypto_recv(
41482498Sroberto	struct peer *peer,	/* peer structure pointer */
41582498Sroberto	struct recvbuf *rbufp	/* packet buffer pointer */
41682498Sroberto	)
41782498Sroberto{
418132451Sroberto	const EVP_MD *dp;	/* message digest algorithm */
419132451Sroberto	u_int32	*pkt;		/* receive packet pointer */
420132451Sroberto	struct autokey *ap, *bp; /* autokey pointer */
421132451Sroberto	struct exten *ep, *fp;	/* extension pointers */
422285612Sdelphij	struct cert_info *xinfo; /* certificate info pointer */
423289999Sglebius	int	macbytes;	/* length of MAC field, signed by intention */
424132451Sroberto	int	authlen;	/* offset of MAC field */
425132451Sroberto	associd_t associd;	/* association ID */
426132451Sroberto	tstamp_t fstamp = 0;	/* filestamp */
427132451Sroberto	u_int	len;		/* extension field length */
428132451Sroberto	u_int	code;		/* extension field opcode */
429132451Sroberto	u_int	vallen = 0;	/* value length */
430132451Sroberto	X509	*cert;		/* X509 certificate */
431132451Sroberto	char	statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
432132451Sroberto	keyid_t	cookie;		/* crumbles */
433182007Sroberto	int	hismode;	/* packet mode */
434132451Sroberto	int	rval = XEVNT_OK;
435285612Sdelphij	const u_char *puch;
436132451Sroberto	u_int32 temp32;
43782498Sroberto
43882498Sroberto	/*
43982498Sroberto	 * Initialize. Note that the packet has already been checked for
440132451Sroberto	 * valid format and extension field lengths. First extract the
441132451Sroberto	 * field length, command code and association ID in host byte
442132451Sroberto	 * order. These are used with all commands and modes. Then check
443132451Sroberto	 * the version number, which must be 2, and length, which must
444132451Sroberto	 * be at least 8 for requests and VALUE_LEN (24) for responses.
445132451Sroberto	 * Packets that fail either test sink without a trace. The
446132451Sroberto	 * association ID is saved only if nonzero.
44782498Sroberto	 */
44882498Sroberto	authlen = LEN_PKT_NOMAC;
449182007Sroberto	hismode = (int)PKT_MODE((&rbufp->recv_pkt)->li_vn_mode);
450289999Sglebius	while ((macbytes = rbufp->recv_length - authlen) > (int)MAX_MAC_LEN) {
451289999Sglebius		/* We can be reasonably sure that we can read at least
452289999Sglebius		 * the opcode and the size field here. More stringent
453289999Sglebius		 * checks follow up shortly.
454289999Sglebius		 */
455132451Sroberto		pkt = (u_int32 *)&rbufp->recv_pkt + authlen / 4;
456132451Sroberto		ep = (struct exten *)pkt;
457132451Sroberto		code = ntohl(ep->opcode) & 0xffff0000;
458132451Sroberto		len = ntohl(ep->opcode) & 0x0000ffff;
459285612Sdelphij		// HMS: Why pkt[1] instead of ep->associd ?
460285612Sdelphij		associd = (associd_t)ntohl(pkt[1]);
461132451Sroberto		rval = XEVNT_OK;
462285612Sdelphij		DPRINTF(1, ("crypto_recv: flags 0x%x ext offset %d len %u code 0x%x associd %d\n",
463132451Sroberto			    peer->crypto, authlen, len, code >> 16,
464285612Sdelphij			    associd));
465132451Sroberto
466132451Sroberto		/*
467132451Sroberto		 * Check version number and field length. If bad,
468132451Sroberto		 * quietly ignore the packet.
469132451Sroberto		 */
470182007Sroberto		if (((code >> 24) & 0x3f) != CRYPTO_VN || len < 8) {
471285612Sdelphij			sys_badlength++;
472132451Sroberto			code |= CRYPTO_ERROR;
473132451Sroberto		}
474132451Sroberto
475289999Sglebius		/* Check if the declared size fits into the remaining
476293893Sglebius		 * buffer. We *know* 'macbytes' > 0 here!
477289999Sglebius		 */
478293893Sglebius		if (len > (u_int)macbytes) {
479289999Sglebius			DPRINTF(1, ("crypto_recv: possible attack detected, associd %d\n",
480289999Sglebius				    associd));
481289999Sglebius			return XEVNT_LEN;
482289999Sglebius		}
483289999Sglebius
484289999Sglebius		/* Check if the paylod of the extension fits into the
485289999Sglebius		 * declared frame.
486289999Sglebius		 */
487132451Sroberto		if (len >= VALUE_LEN) {
488132451Sroberto			fstamp = ntohl(ep->fstamp);
489132451Sroberto			vallen = ntohl(ep->vallen);
490281230Sdelphij			/*
491281230Sdelphij			 * Bug 2761: I hope this isn't too early...
492281230Sdelphij			 */
493281230Sdelphij			if (   vallen == 0
494281230Sdelphij			    || len - VALUE_LEN < vallen)
495281230Sdelphij				return XEVNT_LEN;
496132451Sroberto		}
49782498Sroberto		switch (code) {
49882498Sroberto
49982498Sroberto		/*
500132451Sroberto		 * Install status word, host name, signature scheme and
501132451Sroberto		 * association ID. In OpenSSL the signature algorithm is
502132451Sroberto		 * bound to the digest algorithm, so the NID completely
503132451Sroberto		 * defines the signature scheme. Note the request and
504132451Sroberto		 * response are identical, but neither is validated by
505132451Sroberto		 * signature. The request is processed here only in
506182007Sroberto		 * symmetric modes. The server name field might be
507132451Sroberto		 * useful to implement access controls in future.
50882498Sroberto		 */
509132451Sroberto		case CRYPTO_ASSOC:
510132451Sroberto
511132451Sroberto			/*
512285612Sdelphij			 * If our state machine is running when this
513285612Sdelphij			 * message arrives, the other fellow might have
514285612Sdelphij			 * restarted. However, this could be an
515285612Sdelphij			 * intruder, so just clamp the poll interval and
516285612Sdelphij			 * find out for ourselves. Otherwise, pass the
517285612Sdelphij			 * extension field to the transmit side.
518132451Sroberto			 */
519285612Sdelphij			if (peer->crypto & CRYPTO_FLAG_CERT) {
520182007Sroberto				rval = XEVNT_ERR;
521182007Sroberto				break;
522182007Sroberto			}
523285612Sdelphij			if (peer->cmmd) {
524285612Sdelphij				if (peer->assoc != associd) {
525285612Sdelphij					rval = XEVNT_ERR;
526285612Sdelphij					break;
527285612Sdelphij				}
528289999Sglebius				free(peer->cmmd); /* will be set again! */
529285612Sdelphij			}
530132451Sroberto			fp = emalloc(len);
531132451Sroberto			memcpy(fp, ep, len);
532285612Sdelphij			fp->associd = htonl(peer->associd);
533132451Sroberto			peer->cmmd = fp;
534132451Sroberto			/* fall through */
535132451Sroberto
53682498Sroberto		case CRYPTO_ASSOC | CRYPTO_RESP:
537132451Sroberto
538132451Sroberto			/*
539132451Sroberto			 * Discard the message if it has already been
540182007Sroberto			 * stored or the message has been amputated.
541132451Sroberto			 */
542285612Sdelphij			if (peer->crypto) {
543285612Sdelphij				if (peer->assoc != associd)
544285612Sdelphij					rval = XEVNT_ERR;
545132451Sroberto				break;
546285612Sdelphij			}
547285612Sdelphij			INSIST(len >= VALUE_LEN);
548182007Sroberto			if (vallen == 0 || vallen > MAXHOSTNAME ||
549281230Sdelphij			    len - VALUE_LEN < vallen) {
550132451Sroberto				rval = XEVNT_LEN;
551132451Sroberto				break;
55282498Sroberto			}
553285612Sdelphij			DPRINTF(1, ("crypto_recv: ident host 0x%x %d server 0x%x %d\n",
554285612Sdelphij				    crypto_flags, peer->associd, fstamp,
555285612Sdelphij				    peer->assoc));
556285612Sdelphij			temp32 = crypto_flags & CRYPTO_FLAG_MASK;
557132451Sroberto
558132451Sroberto			/*
559285612Sdelphij			 * If the client scheme is PC, the server scheme
560285612Sdelphij			 * must be PC. The public key and identity are
561285612Sdelphij			 * presumed valid, so we skip the certificate
562285612Sdelphij			 * and identity exchanges and move immediately
563285612Sdelphij			 * to the cookie exchange which confirms the
564285612Sdelphij			 * server signature.
565132451Sroberto			 */
566132451Sroberto			if (crypto_flags & CRYPTO_FLAG_PRIV) {
567182007Sroberto				if (!(fstamp & CRYPTO_FLAG_PRIV)) {
568132451Sroberto					rval = XEVNT_KEY;
569182007Sroberto					break;
570285612Sdelphij				}
571285612Sdelphij				fstamp |= CRYPTO_FLAG_CERT |
572285612Sdelphij				    CRYPTO_FLAG_VRFY | CRYPTO_FLAG_SIGN;
573182007Sroberto
574182007Sroberto			/*
575285612Sdelphij			 * It is an error if either peer supports
576285612Sdelphij			 * identity, but the other does not.
577182007Sroberto			 */
578285612Sdelphij			} else if (hismode == MODE_ACTIVE || hismode ==
579285612Sdelphij			    MODE_PASSIVE) {
580285612Sdelphij				if ((temp32 && !(fstamp &
581285612Sdelphij				    CRYPTO_FLAG_MASK)) ||
582285612Sdelphij				    (!temp32 && (fstamp &
583285612Sdelphij				    CRYPTO_FLAG_MASK))) {
584285612Sdelphij					rval = XEVNT_KEY;
585285612Sdelphij					break;
586285612Sdelphij				}
587132451Sroberto			}
588132451Sroberto
589132451Sroberto			/*
590182007Sroberto			 * Discard the message if the signature digest
591182007Sroberto			 * NID is not supported.
592132451Sroberto			 */
593132451Sroberto			temp32 = (fstamp >> 16) & 0xffff;
594132451Sroberto			dp =
595132451Sroberto			    (const EVP_MD *)EVP_get_digestbynid(temp32);
596182007Sroberto			if (dp == NULL) {
597132451Sroberto				rval = XEVNT_MD;
598132451Sroberto				break;
599182007Sroberto			}
600132451Sroberto
601132451Sroberto			/*
602132451Sroberto			 * Save status word, host name and message
603285612Sdelphij			 * digest/signature type. If this is from a
604285612Sdelphij			 * broadcast and the association ID has changed,
605285612Sdelphij			 * request the autokey values.
606132451Sroberto			 */
607285612Sdelphij			peer->assoc = associd;
608285612Sdelphij			if (hismode == MODE_SERVER)
609285612Sdelphij				fstamp |= CRYPTO_FLAG_AUTO;
610285612Sdelphij			if (!(fstamp & CRYPTO_FLAG_TAI))
611285612Sdelphij				fstamp |= CRYPTO_FLAG_LEAP;
612285612Sdelphij			RAND_bytes((u_char *)&peer->hcookie, 4);
613132451Sroberto			peer->crypto = fstamp;
614132451Sroberto			peer->digest = dp;
615285612Sdelphij			if (peer->subject != NULL)
616285612Sdelphij				free(peer->subject);
617132451Sroberto			peer->subject = emalloc(vallen + 1);
618132451Sroberto			memcpy(peer->subject, ep->pkt, vallen);
619132451Sroberto			peer->subject[vallen] = '\0';
620285612Sdelphij			if (peer->issuer != NULL)
621285612Sdelphij				free(peer->issuer);
622285612Sdelphij			peer->issuer = estrdup(peer->subject);
623285612Sdelphij			snprintf(statstr, sizeof(statstr),
624285612Sdelphij			    "assoc %d %d host %s %s", peer->associd,
625285612Sdelphij			    peer->assoc, peer->subject,
626285612Sdelphij			    OBJ_nid2ln(temp32));
627132451Sroberto			record_crypto_stats(&peer->srcadr, statstr);
628285612Sdelphij			DPRINTF(1, ("crypto_recv: %s\n", statstr));
62982498Sroberto			break;
63082498Sroberto
63182498Sroberto		/*
632132451Sroberto		 * Decode X509 certificate in ASN.1 format and extract
633132451Sroberto		 * the data containing, among other things, subject
634132451Sroberto		 * name and public key. In the default identification
635132451Sroberto		 * scheme, the certificate trail is followed to a self
636132451Sroberto		 * signed trusted certificate.
63782498Sroberto		 */
638132451Sroberto		case CRYPTO_CERT | CRYPTO_RESP:
639132451Sroberto
640132451Sroberto			/*
641285612Sdelphij			 * Discard the message if empty or invalid.
642132451Sroberto			 */
643285612Sdelphij			if (len < VALUE_LEN)
644285612Sdelphij				break;
645285612Sdelphij
646132451Sroberto			if ((rval = crypto_verify(ep, NULL, peer)) !=
647132451Sroberto			    XEVNT_OK)
648132451Sroberto				break;
649132451Sroberto
650132451Sroberto			/*
651132451Sroberto			 * Scan the certificate list to delete old
652132451Sroberto			 * versions and link the newest version first on
653285612Sdelphij			 * the list. Then, verify the signature. If the
654285612Sdelphij			 * certificate is bad or missing, just ignore
655285612Sdelphij			 * it.
656132451Sroberto			 */
657285612Sdelphij			if ((xinfo = cert_install(ep, peer)) == NULL) {
658285612Sdelphij				rval = XEVNT_CRT;
659132451Sroberto				break;
660285612Sdelphij			}
661285612Sdelphij			if ((rval = cert_hike(peer, xinfo)) != XEVNT_OK)
662285612Sdelphij				break;
663132451Sroberto
664132451Sroberto			/*
665182007Sroberto			 * We plug in the public key and lifetime from
666132451Sroberto			 * the first certificate received. However, note
667132451Sroberto			 * that this certificate might not be signed by
668132451Sroberto			 * the server, so we can't check the
669132451Sroberto			 * signature/digest NID.
670132451Sroberto			 */
671132451Sroberto			if (peer->pkey == NULL) {
672285612Sdelphij				puch = xinfo->cert.ptr;
673285612Sdelphij				cert = d2i_X509(NULL, &puch,
674285612Sdelphij				    ntohl(xinfo->cert.vallen));
675132451Sroberto				peer->pkey = X509_get_pubkey(cert);
676132451Sroberto				X509_free(cert);
67782498Sroberto			}
678182007Sroberto			peer->flash &= ~TEST8;
679285612Sdelphij			temp32 = xinfo->nid;
680285612Sdelphij			snprintf(statstr, sizeof(statstr),
681285612Sdelphij			    "cert %s %s 0x%x %s (%u) fs %u",
682285612Sdelphij			    xinfo->subject, xinfo->issuer, xinfo->flags,
683132451Sroberto			    OBJ_nid2ln(temp32), temp32,
684132451Sroberto			    ntohl(ep->fstamp));
685132451Sroberto			record_crypto_stats(&peer->srcadr, statstr);
686285612Sdelphij			DPRINTF(1, ("crypto_recv: %s\n", statstr));
68782498Sroberto			break;
68882498Sroberto
68982498Sroberto		/*
690285612Sdelphij		 * Schnorr (IFF) identity scheme. This scheme is
691285612Sdelphij		 * designed for use with shared secret server group keys
692285612Sdelphij		 * and where the certificate may be generated by a third
693285612Sdelphij		 * party. The client sends a challenge to the server,
694285612Sdelphij		 * which performs a calculation and returns the result.
695285612Sdelphij		 * A positive result is possible only if both client and
696132451Sroberto		 * server contain the same secret group key.
69782498Sroberto		 */
698132451Sroberto		case CRYPTO_IFF | CRYPTO_RESP:
69982498Sroberto
700132451Sroberto			/*
701285612Sdelphij			 * Discard the message if invalid.
702132451Sroberto			 */
703132451Sroberto			if ((rval = crypto_verify(ep, NULL, peer)) !=
704132451Sroberto			    XEVNT_OK)
705132451Sroberto				break;
706132451Sroberto
70782498Sroberto			/*
708285612Sdelphij			 * If the challenge matches the response, the
709285612Sdelphij			 * server public key, signature and identity are
710132451Sroberto			 * all verified at the same time. The server is
711132451Sroberto			 * declared trusted, so we skip further
712285612Sdelphij			 * certificate exchanges and move immediately to
713285612Sdelphij			 * the cookie exchange.
71482498Sroberto			 */
715132451Sroberto			if ((rval = crypto_iff(ep, peer)) != XEVNT_OK)
716132451Sroberto				break;
717132451Sroberto
718285612Sdelphij			peer->crypto |= CRYPTO_FLAG_VRFY;
719182007Sroberto			peer->flash &= ~TEST8;
720285612Sdelphij			snprintf(statstr, sizeof(statstr), "iff %s fs %u",
721285612Sdelphij			    peer->issuer, ntohl(ep->fstamp));
722132451Sroberto			record_crypto_stats(&peer->srcadr, statstr);
723285612Sdelphij			DPRINTF(1, ("crypto_recv: %s\n", statstr));
72482498Sroberto			break;
72582498Sroberto
72682498Sroberto		/*
727132451Sroberto		 * Guillou-Quisquater (GQ) identity scheme. This scheme
728132451Sroberto		 * is designed for use with public certificates carrying
729132451Sroberto		 * the GQ public key in an extension field. The client
730132451Sroberto		 * sends a challenge to the server, which performs a
731132451Sroberto		 * calculation and returns the result. A positive result
732132451Sroberto		 * is possible only if both client and server contain
733132451Sroberto		 * the same group key and the server has the matching GQ
734132451Sroberto		 * private key.
73582498Sroberto		 */
736132451Sroberto		case CRYPTO_GQ | CRYPTO_RESP:
737132451Sroberto
738132451Sroberto			/*
739285612Sdelphij			 * Discard the message if invalid
740132451Sroberto			 */
741132451Sroberto			if ((rval = crypto_verify(ep, NULL, peer)) !=
742132451Sroberto			    XEVNT_OK)
743132451Sroberto				break;
744132451Sroberto
745132451Sroberto			/*
746285612Sdelphij			 * If the challenge matches the response, the
747285612Sdelphij			 * server public key, signature and identity are
748132451Sroberto			 * all verified at the same time. The server is
749132451Sroberto			 * declared trusted, so we skip further
750285612Sdelphij			 * certificate exchanges and move immediately to
751285612Sdelphij			 * the cookie exchange.
752132451Sroberto			 */
753132451Sroberto			if ((rval = crypto_gq(ep, peer)) != XEVNT_OK)
754132451Sroberto				break;
755132451Sroberto
756285612Sdelphij			peer->crypto |= CRYPTO_FLAG_VRFY;
757182007Sroberto			peer->flash &= ~TEST8;
758285612Sdelphij			snprintf(statstr, sizeof(statstr), "gq %s fs %u",
759285612Sdelphij			    peer->issuer, ntohl(ep->fstamp));
760132451Sroberto			record_crypto_stats(&peer->srcadr, statstr);
761285612Sdelphij			DPRINTF(1, ("crypto_recv: %s\n", statstr));
76282498Sroberto			break;
76382498Sroberto
76482498Sroberto		/*
765285612Sdelphij		 * Mu-Varadharajan (MV) identity scheme. This scheme is
766285612Sdelphij		 * designed for use with three levels of trust, trusted
767285612Sdelphij		 * host, server and client. The trusted host key is
768285612Sdelphij		 * opaque to servers and clients; the server keys are
769285612Sdelphij		 * opaque to clients and each client key is different.
770285612Sdelphij		 * Client keys can be revoked without requiring new key
771285612Sdelphij		 * generations.
77282498Sroberto		 */
773132451Sroberto		case CRYPTO_MV | CRYPTO_RESP:
774132451Sroberto
775132451Sroberto			/*
776285612Sdelphij			 * Discard the message if invalid.
777132451Sroberto			 */
778132451Sroberto			if ((rval = crypto_verify(ep, NULL, peer)) !=
779132451Sroberto			    XEVNT_OK)
780132451Sroberto				break;
781132451Sroberto
782132451Sroberto			/*
783285612Sdelphij			 * If the challenge matches the response, the
784285612Sdelphij			 * server public key, signature and identity are
785132451Sroberto			 * all verified at the same time. The server is
786132451Sroberto			 * declared trusted, so we skip further
787285612Sdelphij			 * certificate exchanges and move immediately to
788285612Sdelphij			 * the cookie exchange.
789132451Sroberto			 */
790132451Sroberto			if ((rval = crypto_mv(ep, peer)) != XEVNT_OK)
791132451Sroberto				break;
792132451Sroberto
793285612Sdelphij			peer->crypto |= CRYPTO_FLAG_VRFY;
794182007Sroberto			peer->flash &= ~TEST8;
795285612Sdelphij			snprintf(statstr, sizeof(statstr), "mv %s fs %u",
796285612Sdelphij			    peer->issuer, ntohl(ep->fstamp));
797132451Sroberto			record_crypto_stats(&peer->srcadr, statstr);
798285612Sdelphij			DPRINTF(1, ("crypto_recv: %s\n", statstr));
799132451Sroberto			break;
80082498Sroberto
801132451Sroberto
802132451Sroberto		/*
803132451Sroberto		 * Cookie response in client and symmetric modes. If the
804132451Sroberto		 * cookie bit is set, the working cookie is the EXOR of
805132451Sroberto		 * the current and new values.
806132451Sroberto		 */
807132451Sroberto		case CRYPTO_COOK | CRYPTO_RESP:
808132451Sroberto
80982498Sroberto			/*
810285612Sdelphij			 * Discard the message if invalid or signature
811285612Sdelphij			 * not verified with respect to the cookie
812285612Sdelphij			 * values.
81382498Sroberto			 */
814132451Sroberto			if ((rval = crypto_verify(ep, &peer->cookval,
815132451Sroberto			    peer)) != XEVNT_OK)
816132451Sroberto				break;
817132451Sroberto
81882498Sroberto			/*
819132451Sroberto			 * Decrypt the cookie, hunting all the time for
820132451Sroberto			 * errors.
82182498Sroberto			 */
822285612Sdelphij			if (vallen == (u_int)EVP_PKEY_size(host_pkey)) {
823276072Sdelphij				u_int32 *cookiebuf = malloc(
824285612Sdelphij				    RSA_size(host_pkey->pkey.rsa));
825285612Sdelphij				if (!cookiebuf) {
826276072Sdelphij					rval = XEVNT_CKY;
827276072Sdelphij					break;
828276072Sdelphij				}
829285612Sdelphij
830276072Sdelphij				if (RSA_private_decrypt(vallen,
831132451Sroberto				    (u_char *)ep->pkt,
832276072Sdelphij				    (u_char *)cookiebuf,
833132451Sroberto				    host_pkey->pkey.rsa,
834276072Sdelphij				    RSA_PKCS1_OAEP_PADDING) != 4) {
835276072Sdelphij					rval = XEVNT_CKY;
836276072Sdelphij					free(cookiebuf);
837276072Sdelphij					break;
838276072Sdelphij				} else {
839276072Sdelphij					cookie = ntohl(*cookiebuf);
840276072Sdelphij					free(cookiebuf);
841276072Sdelphij				}
842132451Sroberto			} else {
843132451Sroberto				rval = XEVNT_CKY;
844132451Sroberto				break;
845132451Sroberto			}
84682498Sroberto
84782498Sroberto			/*
848132451Sroberto			 * Install cookie values and light the cookie
849132451Sroberto			 * bit. If this is not broadcast client mode, we
850132451Sroberto			 * are done here.
85182498Sroberto			 */
852132451Sroberto			key_expire(peer);
853285612Sdelphij			if (hismode == MODE_ACTIVE || hismode ==
854285612Sdelphij			    MODE_PASSIVE)
855285612Sdelphij				peer->pcookie = peer->hcookie ^ cookie;
856132451Sroberto			else
857132451Sroberto				peer->pcookie = cookie;
858285612Sdelphij			peer->crypto |= CRYPTO_FLAG_COOK;
859182007Sroberto			peer->flash &= ~TEST8;
860285612Sdelphij			snprintf(statstr, sizeof(statstr),
861285612Sdelphij			    "cook %x ts %u fs %u", peer->pcookie,
862285612Sdelphij			    ntohl(ep->tstamp), ntohl(ep->fstamp));
863132451Sroberto			record_crypto_stats(&peer->srcadr, statstr);
864285612Sdelphij			DPRINTF(1, ("crypto_recv: %s\n", statstr));
86582498Sroberto			break;
86682498Sroberto
86782498Sroberto		/*
868132451Sroberto		 * Install autokey values in broadcast client and
869132451Sroberto		 * symmetric modes. We have to do this every time the
870132451Sroberto		 * sever/peer cookie changes or a new keylist is
871132451Sroberto		 * rolled. Ordinarily, this is automatic as this message
872132451Sroberto		 * is piggybacked on the first NTP packet sent upon
873132451Sroberto		 * either of these events. Note that a broadcast client
874132451Sroberto		 * or symmetric peer can receive this response without a
875132451Sroberto		 * matching request.
87682498Sroberto		 */
877132451Sroberto		case CRYPTO_AUTO | CRYPTO_RESP:
87882498Sroberto
879132451Sroberto			/*
880285612Sdelphij			 * Discard the message if invalid or signature
881285612Sdelphij			 * not verified with respect to the receive
882285612Sdelphij			 * autokey values.
883132451Sroberto			 */
884132451Sroberto			if ((rval = crypto_verify(ep, &peer->recval,
885285612Sdelphij			    peer)) != XEVNT_OK)
886132451Sroberto				break;
887132451Sroberto
88882498Sroberto			/*
889285612Sdelphij			 * Discard the message if a broadcast client and
890285612Sdelphij			 * the association ID does not match. This might
891285612Sdelphij			 * happen if a broacast server restarts the
892285612Sdelphij			 * protocol. A protocol restart will occur at
893285612Sdelphij			 * the next ASSOC message.
894285612Sdelphij			 */
895285612Sdelphij			if ((peer->cast_flags & MDF_BCLNT) &&
896285612Sdelphij			    peer->assoc != associd)
897285612Sdelphij				break;
898285612Sdelphij
899285612Sdelphij			/*
900132451Sroberto			 * Install autokey values and light the
901132451Sroberto			 * autokey bit. This is not hard.
90282498Sroberto			 */
903285612Sdelphij			if (ep->tstamp == 0)
904285612Sdelphij				break;
905285612Sdelphij
906132451Sroberto			if (peer->recval.ptr == NULL)
907132451Sroberto				peer->recval.ptr =
908132451Sroberto				    emalloc(sizeof(struct autokey));
909132451Sroberto			bp = (struct autokey *)peer->recval.ptr;
910132451Sroberto			peer->recval.tstamp = ep->tstamp;
911132451Sroberto			peer->recval.fstamp = ep->fstamp;
912132451Sroberto			ap = (struct autokey *)ep->pkt;
913132451Sroberto			bp->seq = ntohl(ap->seq);
914132451Sroberto			bp->key = ntohl(ap->key);
915132451Sroberto			peer->pkeyid = bp->key;
916132451Sroberto			peer->crypto |= CRYPTO_FLAG_AUTO;
917182007Sroberto			peer->flash &= ~TEST8;
918285612Sdelphij			snprintf(statstr, sizeof(statstr),
919132451Sroberto			    "auto seq %d key %x ts %u fs %u", bp->seq,
920132451Sroberto			    bp->key, ntohl(ep->tstamp),
921132451Sroberto			    ntohl(ep->fstamp));
922132451Sroberto			record_crypto_stats(&peer->srcadr, statstr);
923285612Sdelphij			DPRINTF(1, ("crypto_recv: %s\n", statstr));
92482498Sroberto			break;
925182007Sroberto
926182007Sroberto		/*
927182007Sroberto		 * X509 certificate sign response. Validate the
928182007Sroberto		 * certificate signed by the server and install. Later
929182007Sroberto		 * this can be provided to clients of this server in
930182007Sroberto		 * lieu of the self signed certificate in order to
931182007Sroberto		 * validate the public key.
932182007Sroberto		 */
933182007Sroberto		case CRYPTO_SIGN | CRYPTO_RESP:
93482498Sroberto
935182007Sroberto			/*
936285612Sdelphij			 * Discard the message if invalid.
937182007Sroberto			 */
938182007Sroberto			if ((rval = crypto_verify(ep, NULL, peer)) !=
939182007Sroberto			    XEVNT_OK)
940182007Sroberto				break;
941182007Sroberto
942182007Sroberto			/*
943182007Sroberto			 * Scan the certificate list to delete old
944182007Sroberto			 * versions and link the newest version first on
945182007Sroberto			 * the list.
946182007Sroberto			 */
947285612Sdelphij			if ((xinfo = cert_install(ep, peer)) == NULL) {
948285612Sdelphij				rval = XEVNT_CRT;
949182007Sroberto				break;
950285612Sdelphij			}
951182007Sroberto			peer->crypto |= CRYPTO_FLAG_SIGN;
952182007Sroberto			peer->flash &= ~TEST8;
953285612Sdelphij			temp32 = xinfo->nid;
954285612Sdelphij			snprintf(statstr, sizeof(statstr),
955285612Sdelphij			    "sign %s %s 0x%x %s (%u) fs %u",
956285612Sdelphij			    xinfo->subject, xinfo->issuer, xinfo->flags,
957182007Sroberto			    OBJ_nid2ln(temp32), temp32,
958182007Sroberto			    ntohl(ep->fstamp));
959182007Sroberto			record_crypto_stats(&peer->srcadr, statstr);
960285612Sdelphij			DPRINTF(1, ("crypto_recv: %s\n", statstr));
961182007Sroberto			break;
962182007Sroberto
96382498Sroberto		/*
964285612Sdelphij		 * Install leapseconds values. While the leapsecond
965285612Sdelphij		 * values epoch, TAI offset and values expiration epoch
966285612Sdelphij		 * are retained, only the current TAI offset is provided
967285612Sdelphij		 * via the kernel to other applications.
96882498Sroberto		 */
969285612Sdelphij		case CRYPTO_LEAP | CRYPTO_RESP:
970132451Sroberto			/*
971285612Sdelphij			 * Discard the message if invalid. We can't
972285612Sdelphij			 * compare the value timestamps here, as they
973285612Sdelphij			 * can be updated by different servers.
974132451Sroberto			 */
975285612Sdelphij			rval = crypto_verify(ep, NULL, peer);
976285612Sdelphij			if ((rval   != XEVNT_OK          ) ||
977285612Sdelphij			    (vallen != 3*sizeof(uint32_t))  )
978132451Sroberto				break;
979132451Sroberto
980285612Sdelphij			/* Check if we can update the basic TAI offset
981285612Sdelphij			 * for our current leap frame. This is a hack
982285612Sdelphij			 * and ignores the time stamps in the autokey
983285612Sdelphij			 * message.
984132451Sroberto			 */
985285612Sdelphij			if (sys_leap != LEAP_NOTINSYNC)
986285612Sdelphij				leapsec_autokey_tai(ntohl(ep->pkt[0]),
987285612Sdelphij						    rbufp->recv_time.l_ui, NULL);
988285612Sdelphij			tai_leap.tstamp = ep->tstamp;
989285612Sdelphij			tai_leap.fstamp = ep->fstamp;
990285612Sdelphij			crypto_update();
991285612Sdelphij			mprintf_event(EVNT_TAI, peer,
992285612Sdelphij				      "%d seconds", ntohl(ep->pkt[0]));
993132451Sroberto			peer->crypto |= CRYPTO_FLAG_LEAP;
994182007Sroberto			peer->flash &= ~TEST8;
995285612Sdelphij			snprintf(statstr, sizeof(statstr),
996285612Sdelphij				 "leap TAI offset %d at %u expire %u fs %u",
997285612Sdelphij				 ntohl(ep->pkt[0]), ntohl(ep->pkt[1]),
998285612Sdelphij				 ntohl(ep->pkt[2]), ntohl(ep->fstamp));
999132451Sroberto			record_crypto_stats(&peer->srcadr, statstr);
1000285612Sdelphij			DPRINTF(1, ("crypto_recv: %s\n", statstr));
100182498Sroberto			break;
100282498Sroberto
100382498Sroberto		/*
1004132451Sroberto		 * We come here in symmetric modes for miscellaneous
1005132451Sroberto		 * commands that have value fields but are processed on
1006132451Sroberto		 * the transmit side. All we need do here is check for
1007285612Sdelphij		 * valid field length. Note that ASSOC is handled
1008285612Sdelphij		 * separately.
100982498Sroberto		 */
1010182007Sroberto		case CRYPTO_CERT:
1011132451Sroberto		case CRYPTO_IFF:
1012132451Sroberto		case CRYPTO_GQ:
1013132451Sroberto		case CRYPTO_MV:
1014285612Sdelphij		case CRYPTO_COOK:
1015132451Sroberto		case CRYPTO_SIGN:
1016132451Sroberto			if (len < VALUE_LEN) {
1017132451Sroberto				rval = XEVNT_LEN;
101882498Sroberto				break;
1019132451Sroberto			}
1020132451Sroberto			/* fall through */
1021132451Sroberto
1022132451Sroberto		/*
1023285612Sdelphij		 * We come here in symmetric modes for requests
1024285612Sdelphij		 * requiring a response (above plus AUTO and LEAP) and
1025285612Sdelphij		 * for responses. If a request, save the extension field
1026285612Sdelphij		 * for later; invalid requests will be caught on the
1027285612Sdelphij		 * transmit side. If an error or invalid response,
1028285612Sdelphij		 * declare a protocol error.
1029132451Sroberto		 */
1030132451Sroberto		default:
1031132451Sroberto			if (code & (CRYPTO_RESP | CRYPTO_ERROR)) {
1032182007Sroberto				rval = XEVNT_ERR;
1033285612Sdelphij			} else if (peer->cmmd == NULL) {
1034132451Sroberto				fp = emalloc(len);
1035132451Sroberto				memcpy(fp, ep, len);
1036132451Sroberto				peer->cmmd = fp;
1037132451Sroberto			}
103882498Sroberto		}
1039132451Sroberto
1040132451Sroberto		/*
1041132451Sroberto		 * The first error found terminates the extension field
1042285612Sdelphij		 * scan and we return the laundry to the caller.
1043132451Sroberto		 */
1044285612Sdelphij		if (rval != XEVNT_OK) {
1045285612Sdelphij			snprintf(statstr, sizeof(statstr),
1046285612Sdelphij			    "%04x %d %02x %s", htonl(ep->opcode),
1047285612Sdelphij			    associd, rval, eventstr(rval));
1048182007Sroberto			record_crypto_stats(&peer->srcadr, statstr);
1049285612Sdelphij			DPRINTF(1, ("crypto_recv: %s\n", statstr));
1050285612Sdelphij			return (rval);
1051132451Sroberto		}
1052285612Sdelphij		authlen += (len + 3) / 4 * 4;
105382498Sroberto	}
1054132451Sroberto	return (rval);
105582498Sroberto}
105682498Sroberto
105782498Sroberto
105882498Sroberto/*
105982498Sroberto * crypto_xmit - construct extension fields
106082498Sroberto *
106182498Sroberto * This routine is called both when an association is configured and
1062132451Sroberto * when one is not. The only case where this matters is to retrieve the
1063132451Sroberto * autokey information, in which case the caller has to provide the
106482498Sroberto * association ID to match the association.
1065132451Sroberto *
1066285612Sdelphij * Side effect: update the packet offset.
1067285612Sdelphij *
1068285612Sdelphij * Errors
1069285612Sdelphij * XEVNT_OK	success
1070285612Sdelphij * XEVNT_CRT	bad or missing certificate
1071285612Sdelphij * XEVNT_ERR	protocol error
1072285612Sdelphij * XEVNT_LEN	bad field format or length
1073285612Sdelphij * XEVNT_PER	host certificate expired
107482498Sroberto */
1075132451Srobertoint
107682498Srobertocrypto_xmit(
1077285612Sdelphij	struct peer *peer,	/* peer structure pointer */
1078132451Sroberto	struct pkt *xpkt,	/* transmit packet pointer */
1079285612Sdelphij	struct recvbuf *rbufp,	/* receive buffer pointer */
1080132451Sroberto	int	start,		/* offset to extension field */
1081132451Sroberto	struct exten *ep,	/* extension pointer */
1082132451Sroberto	keyid_t cookie		/* session cookie */
108382498Sroberto	)
108482498Sroberto{
1085285612Sdelphij	struct exten *fp;	/* extension pointers */
1086285612Sdelphij	struct cert_info *cp, *xp, *yp; /* cert info/value pointer */
1087285612Sdelphij	sockaddr_u *srcadr_sin; /* source address */
1088132451Sroberto	u_int32	*pkt;		/* packet pointer */
1089132451Sroberto	u_int	opcode;		/* extension field opcode */
1090132451Sroberto	char	certname[MAXHOSTNAME + 1]; /* subject name buffer */
1091132451Sroberto	char	statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1092182007Sroberto	tstamp_t tstamp;
1093285612Sdelphij	struct calendar tscal;
1094132451Sroberto	u_int	vallen;
1095132451Sroberto	struct value vtemp;
1096132451Sroberto	associd_t associd;
1097132451Sroberto	int	rval;
1098285612Sdelphij	int	len;
1099132451Sroberto	keyid_t tcookie;
110082498Sroberto
110182498Sroberto	/*
110282498Sroberto	 * Generate the requested extension field request code, length
1103132451Sroberto	 * and association ID. If this is a response and the host is not
1104132451Sroberto	 * synchronized, light the error bit and go home.
110582498Sroberto	 */
1106132451Sroberto	pkt = (u_int32 *)xpkt + start / 4;
1107132451Sroberto	fp = (struct exten *)pkt;
1108132451Sroberto	opcode = ntohl(ep->opcode);
1109285612Sdelphij	if (peer != NULL) {
1110285612Sdelphij		srcadr_sin = &peer->srcadr;
1111285612Sdelphij		if (!(opcode & CRYPTO_RESP))
1112285612Sdelphij			peer->opcode = ep->opcode;
1113285612Sdelphij	} else {
1114285612Sdelphij		srcadr_sin = &rbufp->recv_srcadr;
1115285612Sdelphij	}
1116132451Sroberto	associd = (associd_t) ntohl(ep->associd);
111782498Sroberto	len = 8;
1118285612Sdelphij	fp->opcode = htonl((opcode & 0xffff0000) | len);
1119285612Sdelphij	fp->associd = ep->associd;
1120132451Sroberto	rval = XEVNT_OK;
1121182007Sroberto	tstamp = crypto_time();
1122132451Sroberto	switch (opcode & 0xffff0000) {
112382498Sroberto
112482498Sroberto	/*
1125132451Sroberto	 * Send association request and response with status word and
1126132451Sroberto	 * host name. Note, this message is not signed and the filestamp
1127182007Sroberto	 * contains only the status word.
112882498Sroberto	 */
1129285612Sdelphij	case CRYPTO_ASSOC:
113082498Sroberto	case CRYPTO_ASSOC | CRYPTO_RESP:
1131285612Sdelphij		len = crypto_send(fp, &hostval, start);
1132182007Sroberto		fp->fstamp = htonl(crypto_flags);
1133182007Sroberto		break;
1134182007Sroberto
113582498Sroberto	/*
1136132451Sroberto	 * Send certificate request. Use the values from the extension
1137132451Sroberto	 * field.
113882498Sroberto	 */
1139132451Sroberto	case CRYPTO_CERT:
1140132451Sroberto		memset(&vtemp, 0, sizeof(vtemp));
1141132451Sroberto		vtemp.tstamp = ep->tstamp;
1142132451Sroberto		vtemp.fstamp = ep->fstamp;
1143132451Sroberto		vtemp.vallen = ep->vallen;
1144182007Sroberto		vtemp.ptr = (u_char *)ep->pkt;
1145285612Sdelphij		len = crypto_send(fp, &vtemp, start);
1146132451Sroberto		break;
1147132451Sroberto
1148132451Sroberto	/*
1149285612Sdelphij	 * Send sign request. Use the host certificate, which is self-
1150285612Sdelphij	 * signed and may or may not be trusted.
1151132451Sroberto	 */
1152132451Sroberto	case CRYPTO_SIGN:
1153285612Sdelphij		(void)ntpcal_ntp_to_date(&tscal, tstamp, NULL);
1154285612Sdelphij		if ((calcomp(&tscal, &(cert_host->first)) < 0)
1155285612Sdelphij		|| (calcomp(&tscal, &(cert_host->last)) > 0))
1156285612Sdelphij			rval = XEVNT_PER;
1157285612Sdelphij		else
1158285612Sdelphij			len = crypto_send(fp, &cert_host->cert, start);
1159285612Sdelphij		break;
1160285612Sdelphij
1161285612Sdelphij	/*
1162285612Sdelphij	 * Send certificate response. Use the name in the extension
1163285612Sdelphij	 * field to find the certificate in the cache. If the request
1164285612Sdelphij	 * contains no subject name, assume the name of this host. This
1165285612Sdelphij	 * is for backwards compatibility. Private certificates are
1166285612Sdelphij	 * never sent.
1167285612Sdelphij	 *
1168285612Sdelphij	 * There may be several certificates matching the request. First
1169285612Sdelphij	 * choice is a self-signed trusted certificate; second choice is
1170285612Sdelphij	 * any certificate signed by another host. There is no third
1171285612Sdelphij	 * choice.
1172285612Sdelphij	 */
1173132451Sroberto	case CRYPTO_CERT | CRYPTO_RESP:
1174289999Sglebius		vallen = exten_payload_size(ep); /* Must be <64k */
1175289999Sglebius		if (vallen == 0 || vallen >= sizeof(certname) ) {
1176182007Sroberto			rval = XEVNT_LEN;
117782498Sroberto			break;
117882498Sroberto		}
1179182007Sroberto
1180182007Sroberto		/*
1181285612Sdelphij		 * Find all public valid certificates with matching
1182285612Sdelphij		 * subject. If a self-signed, trusted certificate is
1183285612Sdelphij		 * found, use that certificate. If not, use the last non
1184285612Sdelphij		 * self-signed certificate.
1185182007Sroberto		 */
1186285612Sdelphij		memcpy(certname, ep->pkt, vallen);
1187285612Sdelphij		certname[vallen] = '\0';
1188285612Sdelphij		xp = yp = NULL;
1189132451Sroberto		for (cp = cinfo; cp != NULL; cp = cp->link) {
1190285612Sdelphij			if (cp->flags & (CERT_PRIV | CERT_ERROR))
1191132451Sroberto				continue;
1192182007Sroberto
1193285612Sdelphij			if (strcmp(certname, cp->subject) != 0)
1194285612Sdelphij				continue;
1195285612Sdelphij
1196285612Sdelphij			if (strcmp(certname, cp->issuer) != 0)
1197285612Sdelphij				yp = cp;
1198285612Sdelphij			else if (cp ->flags & CERT_TRUST)
1199285612Sdelphij				xp = cp;
1200285612Sdelphij			continue;
1201132451Sroberto		}
1202182007Sroberto
1203182007Sroberto		/*
1204285612Sdelphij		 * Be careful who you trust. If the certificate is not
1205285612Sdelphij		 * found, return an empty response. Note that we dont
1206285612Sdelphij		 * enforce lifetimes here.
1207182007Sroberto		 *
1208285612Sdelphij		 * The timestamp and filestamp are taken from the
1209182007Sroberto		 * certificate value structure. For all certificates the
1210182007Sroberto		 * timestamp is the latest signature update time. For
1211182007Sroberto		 * host and imported certificates the filestamp is the
1212182007Sroberto		 * creation epoch. For signed certificates the filestamp
1213182007Sroberto		 * is the creation epoch of the trusted certificate at
1214285612Sdelphij		 * the root of the certificate trail. In principle, this
1215182007Sroberto		 * allows strong checking for signature masquerade.
1216182007Sroberto		 */
1217285612Sdelphij		if (xp == NULL)
1218285612Sdelphij			xp = yp;
1219285612Sdelphij		if (xp == NULL)
1220285612Sdelphij			break;
1221285612Sdelphij
1222182007Sroberto		if (tstamp == 0)
1223182007Sroberto			break;
1224182007Sroberto
1225285612Sdelphij		len = crypto_send(fp, &xp->cert, start);
122682498Sroberto		break;
122782498Sroberto
122882498Sroberto	/*
1229132451Sroberto	 * Send challenge in Schnorr (IFF) identity scheme.
123082498Sroberto	 */
1231132451Sroberto	case CRYPTO_IFF:
1232285612Sdelphij		if (peer == NULL)
1233285612Sdelphij			break;		/* hack attack */
1234285612Sdelphij
1235182007Sroberto		if ((rval = crypto_alice(peer, &vtemp)) == XEVNT_OK) {
1236285612Sdelphij			len = crypto_send(fp, &vtemp, start);
1237182007Sroberto			value_free(&vtemp);
1238182007Sroberto		}
123982498Sroberto		break;
124082498Sroberto
124182498Sroberto	/*
1242132451Sroberto	 * Send response in Schnorr (IFF) identity scheme.
124382498Sroberto	 */
1244132451Sroberto	case CRYPTO_IFF | CRYPTO_RESP:
1245182007Sroberto		if ((rval = crypto_bob(ep, &vtemp)) == XEVNT_OK) {
1246285612Sdelphij			len = crypto_send(fp, &vtemp, start);
1247182007Sroberto			value_free(&vtemp);
1248182007Sroberto		}
1249132451Sroberto		break;
1250132451Sroberto
125182498Sroberto	/*
1252132451Sroberto	 * Send challenge in Guillou-Quisquater (GQ) identity scheme.
125382498Sroberto	 */
1254132451Sroberto	case CRYPTO_GQ:
1255285612Sdelphij		if (peer == NULL)
1256285612Sdelphij			break;		/* hack attack */
1257285612Sdelphij
1258182007Sroberto		if ((rval = crypto_alice2(peer, &vtemp)) == XEVNT_OK) {
1259285612Sdelphij			len = crypto_send(fp, &vtemp, start);
1260182007Sroberto			value_free(&vtemp);
1261182007Sroberto		}
126282498Sroberto		break;
126382498Sroberto
126482498Sroberto	/*
1265132451Sroberto	 * Send response in Guillou-Quisquater (GQ) identity scheme.
126682498Sroberto	 */
1267132451Sroberto	case CRYPTO_GQ | CRYPTO_RESP:
1268182007Sroberto		if ((rval = crypto_bob2(ep, &vtemp)) == XEVNT_OK) {
1269285612Sdelphij			len = crypto_send(fp, &vtemp, start);
1270182007Sroberto			value_free(&vtemp);
1271182007Sroberto		}
1272132451Sroberto		break;
1273132451Sroberto
1274132451Sroberto	/*
1275132451Sroberto	 * Send challenge in MV identity scheme.
1276132451Sroberto	 */
1277132451Sroberto	case CRYPTO_MV:
1278285612Sdelphij		if (peer == NULL)
1279285612Sdelphij			break;		/* hack attack */
1280285612Sdelphij
1281182007Sroberto		if ((rval = crypto_alice3(peer, &vtemp)) == XEVNT_OK) {
1282285612Sdelphij			len = crypto_send(fp, &vtemp, start);
1283182007Sroberto			value_free(&vtemp);
1284182007Sroberto		}
128582498Sroberto		break;
128682498Sroberto
128782498Sroberto	/*
1288132451Sroberto	 * Send response in MV identity scheme.
128982498Sroberto	 */
1290132451Sroberto	case CRYPTO_MV | CRYPTO_RESP:
1291182007Sroberto		if ((rval = crypto_bob3(ep, &vtemp)) == XEVNT_OK) {
1292285612Sdelphij			len = crypto_send(fp, &vtemp, start);
1293182007Sroberto			value_free(&vtemp);
1294182007Sroberto		}
1295132451Sroberto		break;
1296132451Sroberto
1297132451Sroberto	/*
1298132451Sroberto	 * Send certificate sign response. The integrity of the request
1299132451Sroberto	 * certificate has already been verified on the receive side.
1300132451Sroberto	 * Sign the response using the local server key. Use the
1301132451Sroberto	 * filestamp from the request and use the timestamp as the
1302132451Sroberto	 * current time. Light the error bit if the certificate is
1303132451Sroberto	 * invalid or contains an unverified signature.
1304132451Sroberto	 */
1305132451Sroberto	case CRYPTO_SIGN | CRYPTO_RESP:
1306285612Sdelphij		if ((rval = cert_sign(ep, &vtemp)) == XEVNT_OK) {
1307285612Sdelphij			len = crypto_send(fp, &vtemp, start);
1308285612Sdelphij			value_free(&vtemp);
1309285612Sdelphij		}
1310132451Sroberto		break;
1311132451Sroberto
1312132451Sroberto	/*
1313132451Sroberto	 * Send public key and signature. Use the values from the public
1314132451Sroberto	 * key.
1315132451Sroberto	 */
1316132451Sroberto	case CRYPTO_COOK:
1317285612Sdelphij		len = crypto_send(fp, &pubkey, start);
1318132451Sroberto		break;
1319132451Sroberto
1320132451Sroberto	/*
1321132451Sroberto	 * Encrypt and send cookie and signature. Light the error bit if
1322132451Sroberto	 * anything goes wrong.
1323132451Sroberto	 */
1324132451Sroberto	case CRYPTO_COOK | CRYPTO_RESP:
1325281230Sdelphij		vallen = ntohl(ep->vallen);	/* Must be <64k */
1326281230Sdelphij		if (   vallen == 0
1327281230Sdelphij		    || (vallen >= MAX_VALLEN)
1328281230Sdelphij		    || (opcode & 0x0000ffff)  < VALUE_LEN + vallen) {
1329182007Sroberto			rval = XEVNT_LEN;
133082498Sroberto			break;
133182498Sroberto		}
1332285612Sdelphij		if (peer == NULL)
1333132451Sroberto			tcookie = cookie;
1334285612Sdelphij		else
1335285612Sdelphij			tcookie = peer->hcookie;
1336281230Sdelphij		if ((rval = crypto_encrypt((const u_char *)ep->pkt, vallen, &tcookie, &vtemp))
1337281230Sdelphij		    == XEVNT_OK) {
1338285612Sdelphij			len = crypto_send(fp, &vtemp, start);
1339281230Sdelphij			value_free(&vtemp);
1340281230Sdelphij		}
134182498Sroberto		break;
134282498Sroberto
134382498Sroberto	/*
1344132451Sroberto	 * Find peer and send autokey data and signature in broadcast
1345132451Sroberto	 * server and symmetric modes. Use the values in the autokey
1346132451Sroberto	 * structure. If no association is found, either the server has
1347132451Sroberto	 * restarted with new associations or some perp has replayed an
1348132451Sroberto	 * old message, in which case light the error bit.
134982498Sroberto	 */
1350132451Sroberto	case CRYPTO_AUTO | CRYPTO_RESP:
1351285612Sdelphij		if (peer == NULL) {
1352285612Sdelphij			if ((peer = findpeerbyassoc(associd)) == NULL) {
1353285612Sdelphij				rval = XEVNT_ERR;
1354285612Sdelphij				break;
1355285612Sdelphij			}
135682498Sroberto		}
1357132451Sroberto		peer->flags &= ~FLAG_ASSOC;
1358285612Sdelphij		len = crypto_send(fp, &peer->sndval, start);
135982498Sroberto		break;
136082498Sroberto
136182498Sroberto	/*
1362285612Sdelphij	 * Send leapseconds values and signature. Use the values from
1363285612Sdelphij	 * the tai structure. If no table has been loaded, just send an
1364182007Sroberto	 * empty request.
136582498Sroberto	 */
1366285612Sdelphij	case CRYPTO_LEAP | CRYPTO_RESP:
1367285612Sdelphij		len = crypto_send(fp, &tai_leap, start);
136882498Sroberto		break;
136982498Sroberto
137082498Sroberto	/*
1371285612Sdelphij	 * Default - Send a valid command for unknown requests; send
1372285612Sdelphij	 * an error response for unknown resonses.
137382498Sroberto	 */
137482498Sroberto	default:
137582498Sroberto		if (opcode & CRYPTO_RESP)
1376182007Sroberto			rval = XEVNT_ERR;
137782498Sroberto	}
137882498Sroberto
137982498Sroberto	/*
1380182007Sroberto	 * In case of error, flame the log. If a request, toss the
1381182007Sroberto	 * puppy; if a response, return so the sender can flame, too.
1382132451Sroberto	 */
1383182007Sroberto	if (rval != XEVNT_OK) {
1384285612Sdelphij		u_int32	uint32;
1385285612Sdelphij
1386285612Sdelphij		uint32 = CRYPTO_ERROR;
1387285612Sdelphij		opcode |= uint32;
1388285612Sdelphij		fp->opcode |= htonl(uint32);
1389285612Sdelphij		snprintf(statstr, sizeof(statstr),
1390285612Sdelphij		    "%04x %d %02x %s", opcode, associd, rval,
1391285612Sdelphij		    eventstr(rval));
1392132451Sroberto		record_crypto_stats(srcadr_sin, statstr);
1393285612Sdelphij		DPRINTF(1, ("crypto_xmit: %s\n", statstr));
1394182007Sroberto		if (!(opcode & CRYPTO_RESP))
1395182007Sroberto			return (0);
1396132451Sroberto	}
1397285612Sdelphij	DPRINTF(1, ("crypto_xmit: flags 0x%x offset %d len %d code 0x%x associd %d\n",
1398285612Sdelphij		    crypto_flags, start, len, opcode >> 16, associd));
139982498Sroberto	return (len);
140082498Sroberto}
140182498Sroberto
1402132451Sroberto
140382498Sroberto/*
1404285612Sdelphij * crypto_verify - verify the extension field value and signature
1405132451Sroberto *
1406132451Sroberto * Returns
1407132451Sroberto * XEVNT_OK	success
1408285612Sdelphij * XEVNT_ERR	protocol error
1409285612Sdelphij * XEVNT_FSP	bad filestamp
1410132451Sroberto * XEVNT_LEN	bad field format or length
1411132451Sroberto * XEVNT_PUB	bad or missing public key
1412132451Sroberto * XEVNT_SGL	bad signature length
1413132451Sroberto * XEVNT_SIG	signature not verified
1414285612Sdelphij * XEVNT_TSP	bad timestamp
141582498Sroberto */
1416132451Srobertostatic int
1417132451Srobertocrypto_verify(
1418132451Sroberto	struct exten *ep,	/* extension pointer */
1419132451Sroberto	struct value *vp,	/* value pointer */
1420132451Sroberto	struct peer *peer	/* peer structure pointer */
1421132451Sroberto	)
142282498Sroberto{
1423132451Sroberto	EVP_PKEY *pkey;		/* server public key */
1424132451Sroberto	EVP_MD_CTX ctx;		/* signature context */
1425182007Sroberto	tstamp_t tstamp, tstamp1 = 0; /* timestamp */
1426182007Sroberto	tstamp_t fstamp, fstamp1 = 0; /* filestamp */
1427132451Sroberto	u_int	vallen;		/* value length */
1428132451Sroberto	u_int	siglen;		/* signature length */
1429132451Sroberto	u_int	opcode, len;
1430132451Sroberto	int	i;
143182498Sroberto
143282498Sroberto	/*
1433285612Sdelphij	 * We are extremely parannoyed. We require valid opcode, length,
1434285612Sdelphij	 * association ID, timestamp, filestamp, public key, digest,
1435285612Sdelphij	 * signature length and signature, where relevant. Note that
1436285612Sdelphij	 * preliminary length checks are done in the main loop.
143782498Sroberto	 */
1438132451Sroberto	len = ntohl(ep->opcode) & 0x0000ffff;
1439132451Sroberto	opcode = ntohl(ep->opcode) & 0xffff0000;
144082498Sroberto
144182498Sroberto	/*
1442285612Sdelphij	 * Check for valid value header, association ID and extension
1443285612Sdelphij	 * field length. Remember, it is not an error to receive an
1444285612Sdelphij	 * unsolicited response; however, the response ID must match
1445285612Sdelphij	 * the association ID.
144682498Sroberto	 */
1447132451Sroberto	if (opcode & CRYPTO_ERROR)
1448182007Sroberto		return (XEVNT_ERR);
1449182007Sroberto
1450285612Sdelphij 	if (len < VALUE_LEN)
1451285612Sdelphij		return (XEVNT_LEN);
1452285612Sdelphij
1453285612Sdelphij	if (opcode == (CRYPTO_AUTO | CRYPTO_RESP) && (peer->pmode ==
1454285612Sdelphij	    MODE_BROADCAST || (peer->cast_flags & MDF_BCLNT))) {
1455285612Sdelphij		if (ntohl(ep->associd) != peer->assoc)
1456285612Sdelphij			return (XEVNT_ERR);
1457132451Sroberto	} else {
1458285612Sdelphij		if (ntohl(ep->associd) != peer->associd)
1459285612Sdelphij			return (XEVNT_ERR);
1460132451Sroberto	}
1461182007Sroberto
1462132451Sroberto	/*
1463285612Sdelphij	 * We have a valid value header. Check for valid value and
1464285612Sdelphij	 * signature field lengths. The extension field length must be
1465285612Sdelphij	 * long enough to contain the value header, value and signature.
1466285612Sdelphij	 * Note both the value and signature field lengths are rounded
1467285612Sdelphij	 * up to the next word (4 octets).
1468132451Sroberto	 */
1469132451Sroberto	vallen = ntohl(ep->vallen);
1470281230Sdelphij	if (   vallen == 0
1471281230Sdelphij	    || vallen > MAX_VALLEN)
1472281230Sdelphij		return (XEVNT_LEN);
1473285612Sdelphij
1474132451Sroberto	i = (vallen + 3) / 4;
1475132451Sroberto	siglen = ntohl(ep->pkt[i++]);
1476281230Sdelphij	if (   siglen > MAX_VALLEN
1477281230Sdelphij	    || len - VALUE_LEN < ((vallen + 3) / 4) * 4
1478281230Sdelphij	    || len - VALUE_LEN - ((vallen + 3) / 4) * 4
1479281230Sdelphij	      < ((siglen + 3) / 4) * 4)
1480132451Sroberto		return (XEVNT_LEN);
1481132451Sroberto
1482182007Sroberto	/*
1483182007Sroberto	 * Check for valid timestamp and filestamp. If the timestamp is
1484182007Sroberto	 * zero, the sender is not synchronized and signatures are
1485285612Sdelphij	 * not possible. If nonzero the timestamp must not precede the
1486182007Sroberto	 * filestamp. The timestamp and filestamp must not precede the
1487285612Sdelphij	 * corresponding values in the value structure, if present.
1488285612Sdelphij 	 */
1489182007Sroberto	tstamp = ntohl(ep->tstamp);
1490182007Sroberto	fstamp = ntohl(ep->fstamp);
1491182007Sroberto	if (tstamp == 0)
1492285612Sdelphij		return (XEVNT_TSP);
1493182007Sroberto
1494182007Sroberto	if (tstamp < fstamp)
1495182007Sroberto		return (XEVNT_TSP);
1496182007Sroberto
1497182007Sroberto	if (vp != NULL) {
1498182007Sroberto		tstamp1 = ntohl(vp->tstamp);
1499182007Sroberto		fstamp1 = ntohl(vp->fstamp);
1500285612Sdelphij		if (tstamp1 != 0 && fstamp1 != 0) {
1501285612Sdelphij			if (tstamp < tstamp1)
1502285612Sdelphij				return (XEVNT_TSP);
1503182007Sroberto
1504285612Sdelphij			if ((tstamp < fstamp1 || fstamp < fstamp1))
1505285612Sdelphij				return (XEVNT_FSP);
1506285612Sdelphij		}
1507182007Sroberto	}
1508182007Sroberto
1509182007Sroberto	/*
1510285612Sdelphij	 * At the time the certificate message is validated, the public
1511285612Sdelphij	 * key in the message is not available. Thus, don't try to
1512285612Sdelphij	 * verify the signature.
1513285612Sdelphij	 */
1514285612Sdelphij	if (opcode == (CRYPTO_CERT | CRYPTO_RESP))
1515285612Sdelphij		return (XEVNT_OK);
1516285612Sdelphij
1517285612Sdelphij	/*
1518182007Sroberto	 * Check for valid signature length, public key and digest
1519182007Sroberto	 * algorithm.
1520182007Sroberto	 */
1521132451Sroberto	if (crypto_flags & peer->crypto & CRYPTO_FLAG_PRIV)
1522132451Sroberto		pkey = sign_pkey;
1523132451Sroberto	else
1524132451Sroberto		pkey = peer->pkey;
1525182007Sroberto	if (siglen == 0 || pkey == NULL || peer->digest == NULL)
1526285612Sdelphij		return (XEVNT_ERR);
1527132451Sroberto
1528182007Sroberto	if (siglen != (u_int)EVP_PKEY_size(pkey))
1529182007Sroberto		return (XEVNT_SGL);
1530182007Sroberto
1531132451Sroberto	/*
1532182007Sroberto	 * Darn, I thought we would never get here. Verify the
1533182007Sroberto	 * signature. If the identity exchange is verified, light the
1534285612Sdelphij	 * proventic bit. What a relief.
1535132451Sroberto	 */
1536182007Sroberto	EVP_VerifyInit(&ctx, peer->digest);
1537281230Sdelphij	/* XXX: the "+ 12" needs to be at least documented... */
1538182007Sroberto	EVP_VerifyUpdate(&ctx, (u_char *)&ep->tstamp, vallen + 12);
1539285612Sdelphij	if (EVP_VerifyFinal(&ctx, (u_char *)&ep->pkt[i], siglen,
1540285612Sdelphij	    pkey) <= 0)
1541182007Sroberto		return (XEVNT_SIG);
1542182007Sroberto
1543285612Sdelphij	if (peer->crypto & CRYPTO_FLAG_VRFY)
1544182007Sroberto		peer->crypto |= CRYPTO_FLAG_PROV;
1545182007Sroberto	return (XEVNT_OK);
1546132451Sroberto}
1547132451Sroberto
1548132451Sroberto
1549132451Sroberto/*
1550281230Sdelphij * crypto_encrypt - construct vp (encrypted cookie and signature) from
1551281230Sdelphij * the public key and cookie.
1552132451Sroberto *
1553281230Sdelphij * Returns:
1554132451Sroberto * XEVNT_OK	success
1555285612Sdelphij * XEVNT_CKY	bad or missing cookie
1556132451Sroberto * XEVNT_PUB	bad or missing public key
1557132451Sroberto */
1558132451Srobertostatic int
1559132451Srobertocrypto_encrypt(
1560281230Sdelphij	const u_char *ptr,	/* Public Key */
1561281230Sdelphij	u_int	vallen,		/* Length of Public Key */
1562281230Sdelphij	keyid_t	*cookie,	/* server cookie */
1563281230Sdelphij	struct value *vp	/* value pointer */
1564132451Sroberto	)
1565132451Sroberto{
1566132451Sroberto	EVP_PKEY *pkey;		/* public key */
1567132451Sroberto	EVP_MD_CTX ctx;		/* signature context */
1568132451Sroberto	tstamp_t tstamp;	/* NTP timestamp */
1569132451Sroberto	u_int32	temp32;
1570285612Sdelphij	u_char *puch;
1571132451Sroberto
1572132451Sroberto	/*
1573132451Sroberto	 * Extract the public key from the request.
1574132451Sroberto	 */
1575281230Sdelphij	pkey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &ptr, vallen);
1576132451Sroberto	if (pkey == NULL) {
1577285612Sdelphij		msyslog(LOG_ERR, "crypto_encrypt: %s",
1578132451Sroberto		    ERR_error_string(ERR_get_error(), NULL));
1579132451Sroberto		return (XEVNT_PUB);
158082498Sroberto	}
158182498Sroberto
158282498Sroberto	/*
1583132451Sroberto	 * Encrypt the cookie, encode in ASN.1 and sign.
158482498Sroberto	 */
1585285612Sdelphij	memset(vp, 0, sizeof(struct value));
1586132451Sroberto	tstamp = crypto_time();
1587132451Sroberto	vp->tstamp = htonl(tstamp);
1588132451Sroberto	vp->fstamp = hostval.tstamp;
1589281230Sdelphij	vallen = EVP_PKEY_size(pkey);
1590281230Sdelphij	vp->vallen = htonl(vallen);
1591281230Sdelphij	vp->ptr = emalloc(vallen);
1592285612Sdelphij	puch = vp->ptr;
1593132451Sroberto	temp32 = htonl(*cookie);
1594285612Sdelphij	if (RSA_public_encrypt(4, (u_char *)&temp32, puch,
1595285612Sdelphij	    pkey->pkey.rsa, RSA_PKCS1_OAEP_PADDING) <= 0) {
1596285612Sdelphij		msyslog(LOG_ERR, "crypto_encrypt: %s",
1597132451Sroberto		    ERR_error_string(ERR_get_error(), NULL));
1598285612Sdelphij		free(vp->ptr);
1599132451Sroberto		EVP_PKEY_free(pkey);
1600132451Sroberto		return (XEVNT_CKY);
1601132451Sroberto	}
1602132451Sroberto	EVP_PKEY_free(pkey);
1603132451Sroberto	if (tstamp == 0)
1604132451Sroberto		return (XEVNT_OK);
1605182007Sroberto
1606132451Sroberto	vp->sig = emalloc(sign_siglen);
1607132451Sroberto	EVP_SignInit(&ctx, sign_digest);
1608132451Sroberto	EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
1609281230Sdelphij	EVP_SignUpdate(&ctx, vp->ptr, vallen);
1610285612Sdelphij	if (EVP_SignFinal(&ctx, vp->sig, &vallen, sign_pkey)) {
1611289999Sglebius		INSIST(vallen <= sign_siglen);
1612285612Sdelphij		vp->siglen = htonl(vallen);
1613285612Sdelphij	}
1614132451Sroberto	return (XEVNT_OK);
1615132451Sroberto}
161682498Sroberto
1617132451Sroberto
1618132451Sroberto/*
1619132451Sroberto * crypto_ident - construct extension field for identity scheme
1620132451Sroberto *
1621132451Sroberto * This routine determines which identity scheme is in use and
1622132451Sroberto * constructs an extension field for that scheme.
1623285612Sdelphij *
1624285612Sdelphij * Returns
1625285612Sdelphij * CRYTPO_IFF	IFF scheme
1626285612Sdelphij * CRYPTO_GQ	GQ scheme
1627285612Sdelphij * CRYPTO_MV	MV scheme
1628285612Sdelphij * CRYPTO_NULL	no available scheme
1629132451Sroberto */
1630132451Srobertou_int
1631132451Srobertocrypto_ident(
1632132451Sroberto	struct peer *peer	/* peer structure pointer */
1633132451Sroberto	)
1634132451Sroberto{
1635285612Sdelphij	char		filename[MAXFILENAME];
1636285612Sdelphij	const char *	scheme_name;
1637285612Sdelphij	u_int		scheme_id;
1638132451Sroberto
163982498Sroberto	/*
1640285612Sdelphij	 * We come here after the group trusted host has been found; its
1641285612Sdelphij	 * name defines the group name. Search the key cache for all
1642285612Sdelphij	 * keys matching the same group name in order IFF, GQ and MV.
1643285612Sdelphij	 * Use the first one available.
164482498Sroberto	 */
1645285612Sdelphij	scheme_name = NULL;
1646132451Sroberto	if (peer->crypto & CRYPTO_FLAG_IFF) {
1647285612Sdelphij		scheme_name = "iff";
1648285612Sdelphij		scheme_id = CRYPTO_IFF;
1649285612Sdelphij	} else if (peer->crypto & CRYPTO_FLAG_GQ) {
1650285612Sdelphij		scheme_name = "gq";
1651285612Sdelphij		scheme_id = CRYPTO_GQ;
1652285612Sdelphij	} else if (peer->crypto & CRYPTO_FLAG_MV) {
1653285612Sdelphij		scheme_name = "mv";
1654285612Sdelphij		scheme_id = CRYPTO_MV;
1655132451Sroberto	}
1656132451Sroberto
1657285612Sdelphij	if (scheme_name != NULL) {
1658285612Sdelphij		snprintf(filename, sizeof(filename), "ntpkey_%spar_%s",
1659285612Sdelphij		    scheme_name, peer->ident);
1660285612Sdelphij		peer->ident_pkey = crypto_key(filename, NULL,
1661285612Sdelphij		    &peer->srcadr);
1662132451Sroberto		if (peer->ident_pkey != NULL)
1663285612Sdelphij			return scheme_id;
1664132451Sroberto	}
1665132451Sroberto
1666285612Sdelphij	msyslog(LOG_NOTICE,
1667285612Sdelphij	    "crypto_ident: no identity parameters found for group %s",
1668285612Sdelphij	    peer->ident);
1669285612Sdelphij
1670285612Sdelphij	return CRYPTO_NULL;
1671132451Sroberto}
167282498Sroberto
1673132451Sroberto
1674132451Sroberto/*
1675132451Sroberto * crypto_args - construct extension field from arguments
1676132451Sroberto *
1677132451Sroberto * This routine creates an extension field with current timestamps and
1678132451Sroberto * specified opcode, association ID and optional string. Note that the
1679132451Sroberto * extension field is created here, but freed after the crypto_xmit()
1680132451Sroberto * call in the protocol module.
1681132451Sroberto *
1682285612Sdelphij * Returns extension field pointer (no errors)
1683281230Sdelphij *
1684281230Sdelphij * XXX: opcode and len should really be 32-bit quantities and
1685281230Sdelphij * we should make sure that str is not too big.
1686132451Sroberto */
1687132451Srobertostruct exten *
1688132451Srobertocrypto_args(
1689132451Sroberto	struct peer *peer,	/* peer structure pointer */
1690132451Sroberto	u_int	opcode,		/* operation code */
1691285612Sdelphij	associd_t associd,	/* association ID */
1692132451Sroberto	char	*str		/* argument string */
1693132451Sroberto	)
1694132451Sroberto{
1695132451Sroberto	tstamp_t tstamp;	/* NTP timestamp */
1696132451Sroberto	struct exten *ep;	/* extension field pointer */
1697132451Sroberto	u_int	len;		/* extension field length */
1698285612Sdelphij	size_t	slen = 0;
1699132451Sroberto
1700132451Sroberto	tstamp = crypto_time();
1701132451Sroberto	len = sizeof(struct exten);
1702281230Sdelphij	if (str != NULL) {
1703281230Sdelphij		slen = strlen(str);
1704285612Sdelphij		INSIST(slen < MAX_VALLEN);
1705281230Sdelphij		len += slen;
1706281230Sdelphij	}
1707285612Sdelphij	ep = emalloc_zero(len);
1708182007Sroberto	if (opcode == 0)
1709182007Sroberto		return (ep);
1710182007Sroberto
1711285612Sdelphij	REQUIRE(0 == (len    & ~0x0000ffff));
1712285612Sdelphij	REQUIRE(0 == (opcode & ~0xffff0000));
1713285612Sdelphij
1714132451Sroberto	ep->opcode = htonl(opcode + len);
1715285612Sdelphij	ep->associd = htonl(associd);
1716132451Sroberto	ep->tstamp = htonl(tstamp);
1717132451Sroberto	ep->fstamp = hostval.tstamp;
1718132451Sroberto	ep->vallen = 0;
1719132451Sroberto	if (str != NULL) {
1720281230Sdelphij		ep->vallen = htonl(slen);
1721281230Sdelphij		memcpy((char *)ep->pkt, str, slen);
1722132451Sroberto	}
1723132451Sroberto	return (ep);
172482498Sroberto}
172582498Sroberto
172682498Sroberto
172782498Sroberto/*
1728132451Sroberto * crypto_send - construct extension field from value components
1729132451Sroberto *
1730285612Sdelphij * The value and signature fields are zero-padded to a word boundary.
1731285612Sdelphij * Note: it is not polite to send a nonempty signature with zero
1732285612Sdelphij * timestamp or a nonzero timestamp with an empty signature, but those
1733285612Sdelphij * rules are not enforced here.
1734281230Sdelphij *
1735281230Sdelphij * XXX This code won't work on a box with 16-bit ints.
173682498Sroberto */
1737285612Sdelphijint
1738132451Srobertocrypto_send(
1739132451Sroberto	struct exten *ep,	/* extension field pointer */
1740285612Sdelphij	struct value *vp,	/* value pointer */
1741285612Sdelphij	int	start		/* buffer offset */
1742132451Sroberto	)
174382498Sroberto{
1744285612Sdelphij	u_int	len, vallen, siglen, opcode;
1745285612Sdelphij	u_int	i, j;
174682498Sroberto
174782498Sroberto	/*
1748285612Sdelphij	 * Calculate extension field length and check for buffer
1749285612Sdelphij	 * overflow. Leave room for the MAC.
175082498Sroberto	 */
1751285612Sdelphij	len = 16;				/* XXX Document! */
1752285612Sdelphij	vallen = ntohl(vp->vallen);
1753285612Sdelphij	INSIST(vallen <= MAX_VALLEN);
1754285612Sdelphij	len += ((vallen + 3) / 4 + 1) * 4;
1755285612Sdelphij	siglen = ntohl(vp->siglen);
1756285612Sdelphij	len += ((siglen + 3) / 4 + 1) * 4;
1757285612Sdelphij	if (start + len > sizeof(struct pkt) - MAX_MAC_LEN)
1758285612Sdelphij		return (0);
1759285612Sdelphij
1760285612Sdelphij	/*
1761285612Sdelphij	 * Copy timestamps.
1762285612Sdelphij	 */
1763132451Sroberto	ep->tstamp = vp->tstamp;
1764132451Sroberto	ep->fstamp = vp->fstamp;
1765132451Sroberto	ep->vallen = vp->vallen;
1766132451Sroberto
1767132451Sroberto	/*
1768285612Sdelphij	 * Copy value. If the data field is empty or zero length,
1769285612Sdelphij	 * encode an empty value with length zero.
1770285612Sdelphij	 */
1771285612Sdelphij	i = 0;
1772285612Sdelphij	if (vallen > 0 && vp->ptr != NULL) {
1773285612Sdelphij		j = vallen / 4;
1774285612Sdelphij		if (j * 4 < vallen)
1775285612Sdelphij			ep->pkt[i + j++] = 0;
1776285612Sdelphij		memcpy(&ep->pkt[i], vp->ptr, vallen);
1777285612Sdelphij		i += j;
1778285612Sdelphij	}
1779285612Sdelphij
1780285612Sdelphij	/*
1781132451Sroberto	 * Copy signature. If the signature field is empty or zero
1782132451Sroberto	 * length, encode an empty signature with length zero.
1783132451Sroberto	 */
1784132451Sroberto	ep->pkt[i++] = vp->siglen;
1785285612Sdelphij	if (siglen > 0 && vp->sig != NULL) {
1786285612Sdelphij		j = siglen / 4;
1787285612Sdelphij		if (j * 4 < siglen)
1788285612Sdelphij			ep->pkt[i + j++] = 0;
1789285612Sdelphij		memcpy(&ep->pkt[i], vp->sig, siglen);
1790289999Sglebius		/* i += j; */	/* We don't use i after this */
1791285612Sdelphij	}
1792285612Sdelphij	opcode = ntohl(ep->opcode);
1793285612Sdelphij	ep->opcode = htonl((opcode & 0xffff0000) | len);
1794285612Sdelphij	ENSURE(len <= MAX_VALLEN);
1795132451Sroberto	return (len);
1796132451Sroberto}
1797132451Sroberto
1798132451Sroberto
1799132451Sroberto/*
1800132451Sroberto * crypto_update - compute new public value and sign extension fields
1801132451Sroberto *
1802132451Sroberto * This routine runs periodically, like once a day, and when something
1803132451Sroberto * changes. It updates the timestamps on three value structures and one
1804132451Sroberto * value structure list, then signs all the structures:
1805132451Sroberto *
1806132451Sroberto * hostval	host name (not signed)
1807132451Sroberto * pubkey	public key
1808132451Sroberto * cinfo	certificate info/value list
1809285612Sdelphij * tai_leap	leap values
1810132451Sroberto *
1811285612Sdelphij * Filestamps are proventic data, so this routine runs only when the
1812285612Sdelphij * host is synchronized to a proventicated source. Thus, the timestamp
1813285612Sdelphij * is proventic and can be used to deflect clogging attacks.
1814132451Sroberto *
1815132451Sroberto * Returns void (no errors)
1816132451Sroberto */
1817132451Srobertovoid
1818132451Srobertocrypto_update(void)
1819132451Sroberto{
1820132451Sroberto	EVP_MD_CTX ctx;		/* message digest context */
1821285612Sdelphij	struct cert_info *cp;	/* certificate info/value */
1822132451Sroberto	char	statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1823285612Sdelphij	u_int32	*ptr;
1824132451Sroberto	u_int	len;
1825285612Sdelphij	leap_result_t leap_data;
1826132451Sroberto
1827285612Sdelphij	hostval.tstamp = htonl(crypto_time());
1828285612Sdelphij	if (hostval.tstamp == 0)
182982498Sroberto		return;
1830182007Sroberto
183182498Sroberto	/*
1832132451Sroberto	 * Sign public key and timestamps. The filestamp is derived from
1833132451Sroberto	 * the host key file extension from wherever the file was
1834132451Sroberto	 * generated.
183582498Sroberto	 */
1836132451Sroberto	if (pubkey.vallen != 0) {
1837132451Sroberto		pubkey.tstamp = hostval.tstamp;
1838132451Sroberto		pubkey.siglen = 0;
1839132451Sroberto		if (pubkey.sig == NULL)
1840132451Sroberto			pubkey.sig = emalloc(sign_siglen);
1841132451Sroberto		EVP_SignInit(&ctx, sign_digest);
1842132451Sroberto		EVP_SignUpdate(&ctx, (u_char *)&pubkey, 12);
1843132451Sroberto		EVP_SignUpdate(&ctx, pubkey.ptr, ntohl(pubkey.vallen));
1844285612Sdelphij		if (EVP_SignFinal(&ctx, pubkey.sig, &len, sign_pkey)) {
1845289999Sglebius			INSIST(len <= sign_siglen);
1846132451Sroberto			pubkey.siglen = htonl(len);
1847285612Sdelphij		}
184882498Sroberto	}
184982498Sroberto
185082498Sroberto	/*
1851132451Sroberto	 * Sign certificates and timestamps. The filestamp is derived
1852132451Sroberto	 * from the certificate file extension from wherever the file
1853182007Sroberto	 * was generated. Note we do not throw expired certificates
1854182007Sroberto	 * away; they may have signed younger ones.
185582498Sroberto	 */
1856285612Sdelphij	for (cp = cinfo; cp != NULL; cp = cp->link) {
1857182007Sroberto		cp->cert.tstamp = hostval.tstamp;
1858182007Sroberto		cp->cert.siglen = 0;
1859182007Sroberto		if (cp->cert.sig == NULL)
1860182007Sroberto			cp->cert.sig = emalloc(sign_siglen);
1861182007Sroberto		EVP_SignInit(&ctx, sign_digest);
1862182007Sroberto		EVP_SignUpdate(&ctx, (u_char *)&cp->cert, 12);
1863182007Sroberto		EVP_SignUpdate(&ctx, cp->cert.ptr,
1864182007Sroberto		    ntohl(cp->cert.vallen));
1865285612Sdelphij		if (EVP_SignFinal(&ctx, cp->cert.sig, &len, sign_pkey)) {
1866289999Sglebius			INSIST(len <= sign_siglen);
1867182007Sroberto			cp->cert.siglen = htonl(len);
1868285612Sdelphij		}
186982498Sroberto	}
187082498Sroberto
187182498Sroberto	/*
1872285612Sdelphij	 * Sign leapseconds values and timestamps. Note it is not an
1873285612Sdelphij	 * error to return null values.
187482498Sroberto	 */
1875285612Sdelphij	tai_leap.tstamp = hostval.tstamp;
1876285612Sdelphij	tai_leap.fstamp = hostval.fstamp;
1877285612Sdelphij
1878285612Sdelphij	/* Get the leap second era. We might need a full lookup early
1879285612Sdelphij	 * after start, when the cache is not yet loaded.
1880285612Sdelphij	 */
1881285612Sdelphij	leapsec_frame(&leap_data);
1882285612Sdelphij	if ( ! memcmp(&leap_data.ebase, &leap_data.ttime, sizeof(vint64))) {
1883285612Sdelphij		time_t   now    = time(NULL);
1884285612Sdelphij		uint32_t nowntp = (uint32_t)now + JAN_1970;
1885285612Sdelphij		leapsec_query(&leap_data, nowntp, &now);
188682498Sroberto	}
1887285612Sdelphij
1888285612Sdelphij	/* Create the data block. The protocol does not work without. */
1889285612Sdelphij	len = 3 * sizeof(u_int32);
1890285612Sdelphij	if (tai_leap.ptr == NULL || ntohl(tai_leap.vallen) != len) {
1891285612Sdelphij		free(tai_leap.ptr);
1892285612Sdelphij		tai_leap.ptr = emalloc(len);
1893285612Sdelphij		tai_leap.vallen = htonl(len);
1894285612Sdelphij	}
1895285612Sdelphij	ptr = (u_int32 *)tai_leap.ptr;
1896285612Sdelphij	if (leap_data.tai_offs > 10) {
1897285612Sdelphij		/* create a TAI / leap era block. The end time is a
1898285612Sdelphij		 * fake -- maybe we can do better.
1899285612Sdelphij		 */
1900285612Sdelphij		ptr[0] = htonl(leap_data.tai_offs);
1901285612Sdelphij		ptr[1] = htonl(leap_data.ebase.d_s.lo);
1902285612Sdelphij		if (leap_data.ttime.d_s.hi >= 0)
1903285612Sdelphij			ptr[2] = htonl(leap_data.ttime.D_s.lo +  7*86400);
1904285612Sdelphij		else
1905285612Sdelphij			ptr[2] = htonl(leap_data.ebase.D_s.lo + 25*86400);
1906285612Sdelphij	} else {
1907285612Sdelphij		/* no leap era available */
1908285612Sdelphij		memset(ptr, 0, len);
1909285612Sdelphij	}
1910285612Sdelphij	if (tai_leap.sig == NULL)
1911285612Sdelphij		tai_leap.sig = emalloc(sign_siglen);
1912285612Sdelphij	EVP_SignInit(&ctx, sign_digest);
1913285612Sdelphij	EVP_SignUpdate(&ctx, (u_char *)&tai_leap, 12);
1914285612Sdelphij	EVP_SignUpdate(&ctx, tai_leap.ptr, len);
1915285612Sdelphij	if (EVP_SignFinal(&ctx, tai_leap.sig, &len, sign_pkey)) {
1916289999Sglebius		INSIST(len <= sign_siglen);
1917285612Sdelphij		tai_leap.siglen = htonl(len);
1918285612Sdelphij	}
1919285612Sdelphij	crypto_flags |= CRYPTO_FLAG_TAI;
1920285612Sdelphij
1921285612Sdelphij	snprintf(statstr, sizeof(statstr), "signature update ts %u",
1922285612Sdelphij	    ntohl(hostval.tstamp));
1923132451Sroberto	record_crypto_stats(NULL, statstr);
1924285612Sdelphij	DPRINTF(1, ("crypto_update: %s\n", statstr));
192582498Sroberto}
192682498Sroberto
1927285612Sdelphij/*
1928285612Sdelphij * crypto_update_taichange - eventually trigger crypto_update
1929285612Sdelphij *
1930285612Sdelphij * This is called when a change in 'sys_tai' is detected. This will
1931285612Sdelphij * happen shortly after a leap second is detected, but unhappily also
1932285612Sdelphij * early after system start; also, the crypto stuff might be unused and
1933285612Sdelphij * an unguarded call to crypto_update() causes a crash.
1934285612Sdelphij *
1935285612Sdelphij * This function makes sure that there already *is* a valid crypto block
1936285612Sdelphij * for the use with autokey, and only calls 'crypto_update()' if it can
1937285612Sdelphij * succeed.
1938285612Sdelphij *
1939285612Sdelphij * Returns void (no errors)
1940285612Sdelphij */
1941285612Sdelphijvoid
1942285612Sdelphijcrypto_update_taichange(void)
1943285612Sdelphij{
1944285612Sdelphij	static const u_int len = 3 * sizeof(u_int32);
194582498Sroberto
1946285612Sdelphij	/* check if the signing digest algo is available */
1947285612Sdelphij	if (sign_digest == NULL || sign_pkey == NULL)
1948285612Sdelphij		return;
1949285612Sdelphij
1950285612Sdelphij	/* check size of TAI extension block */
1951285612Sdelphij	if (tai_leap.ptr == NULL || ntohl(tai_leap.vallen) != len)
1952285612Sdelphij		return;
1953285612Sdelphij
1954285612Sdelphij	/* crypto_update should at least not crash here! */
1955285612Sdelphij	crypto_update();
1956285612Sdelphij}
1957285612Sdelphij
195882498Sroberto/*
1959132451Sroberto * value_free - free value structure components.
1960132451Sroberto *
1961132451Sroberto * Returns void (no errors)
196282498Sroberto */
1963132451Srobertovoid
1964132451Srobertovalue_free(
1965132451Sroberto	struct value *vp	/* value structure */
196682498Sroberto	)
196782498Sroberto{
1968132451Sroberto	if (vp->ptr != NULL)
1969132451Sroberto		free(vp->ptr);
1970132451Sroberto	if (vp->sig != NULL)
1971132451Sroberto		free(vp->sig);
1972132451Sroberto	memset(vp, 0, sizeof(struct value));
1973132451Sroberto}
197482498Sroberto
1975132451Sroberto
1976132451Sroberto/*
1977285612Sdelphij * crypto_time - returns current NTP time.
1978285612Sdelphij *
1979285612Sdelphij * Returns NTP seconds if in synch, 0 otherwise
1980132451Sroberto */
1981132451Srobertotstamp_t
1982132451Srobertocrypto_time()
1983132451Sroberto{
1984285612Sdelphij	l_fp	tstamp;		/* NTP time */
1985132451Sroberto
1986132451Sroberto	L_CLR(&tstamp);
1987132451Sroberto	if (sys_leap != LEAP_NOTINSYNC)
1988132451Sroberto		get_systime(&tstamp);
1989132451Sroberto	return (tstamp.l_ui);
1990132451Sroberto}
1991132451Sroberto
1992132451Sroberto
1993132451Sroberto/*
1994285612Sdelphij * asn_to_calendar - convert ASN1_TIME time structure to struct calendar.
1995285612Sdelphij *
1996132451Sroberto */
1997285612Sdelphijstatic
1998285612Sdelphijvoid
1999285612Sdelphijasn_to_calendar	(
2000285612Sdelphij	ASN1_TIME *asn1time,	/* pointer to ASN1_TIME structure */
2001285612Sdelphij	struct calendar *pjd	/* pointer to result */
2002132451Sroberto	)
2003132451Sroberto{
2004285612Sdelphij	size_t	len;		/* length of ASN1_TIME string */
2005285612Sdelphij	char	v[24];		/* writable copy of ASN1_TIME string */
2006285612Sdelphij	unsigned long	temp;	/* result from strtoul */
2007132451Sroberto
200882498Sroberto	/*
2009132451Sroberto	 * Extract time string YYMMDDHHMMSSZ from ASN1 time structure.
2010285612Sdelphij	 * Or YYYYMMDDHHMMSSZ.
2011132451Sroberto	 * Note that the YY, MM, DD fields start with one, the HH, MM,
2012285612Sdelphij	 * SS fields start with zero and the Z character is ignored.
2013285612Sdelphij	 * Also note that two-digit years less than 50 map to years greater than
2014285612Sdelphij	 * 100. Dontcha love ASN.1? Better than MIL-188.
201582498Sroberto	 */
2016285612Sdelphij	len = asn1time->length;
2017289999Sglebius	REQUIRE(len < sizeof(v));
2018285612Sdelphij	(void)strncpy(v, (char *)(asn1time->data), len);
2019289999Sglebius	REQUIRE(len >= 13);
2020285612Sdelphij	temp = strtoul(v+len-3, NULL, 10);
2021285612Sdelphij	pjd->second = temp;
2022285612Sdelphij	v[len-3] = '\0';
2023182007Sroberto
2024285612Sdelphij	temp = strtoul(v+len-5, NULL, 10);
2025285612Sdelphij	pjd->minute = temp;
2026285612Sdelphij	v[len-5] = '\0';
2027285612Sdelphij
2028285612Sdelphij	temp = strtoul(v+len-7, NULL, 10);
2029285612Sdelphij	pjd->hour = temp;
2030285612Sdelphij	v[len-7] = '\0';
2031285612Sdelphij
2032285612Sdelphij	temp = strtoul(v+len-9, NULL, 10);
2033285612Sdelphij	pjd->monthday = temp;
2034285612Sdelphij	v[len-9] = '\0';
2035285612Sdelphij
2036285612Sdelphij	temp = strtoul(v+len-11, NULL, 10);
2037285612Sdelphij	pjd->month = temp;
2038285612Sdelphij	v[len-11] = '\0';
2039285612Sdelphij
2040285612Sdelphij	temp = strtoul(v, NULL, 10);
2041285612Sdelphij	/* handle two-digit years */
2042285612Sdelphij	if (temp < 50UL)
2043285612Sdelphij	    temp += 100UL;
2044285612Sdelphij	if (temp < 150UL)
2045285612Sdelphij	    temp += 1900UL;
2046285612Sdelphij	pjd->year = temp;
2047285612Sdelphij
2048285612Sdelphij	pjd->yearday = pjd->weekday = 0;
2049285612Sdelphij	return;
2050132451Sroberto}
2051132451Sroberto
2052132451Sroberto
2053132451Sroberto/*
2054132451Sroberto * bigdig() - compute a BIGNUM MD5 hash of a BIGNUM number.
2055285612Sdelphij *
2056285612Sdelphij * Returns void (no errors)
2057132451Sroberto */
2058285612Sdelphijstatic void
2059132451Srobertobighash(
2060132451Sroberto	BIGNUM	*bn,		/* BIGNUM * from */
2061132451Sroberto	BIGNUM	*bk		/* BIGNUM * to */
2062132451Sroberto	)
2063132451Sroberto{
2064132451Sroberto	EVP_MD_CTX ctx;		/* message digest context */
2065132451Sroberto	u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
2066132451Sroberto	u_char	*ptr;		/* a BIGNUM as binary string */
2067132451Sroberto	u_int	len;
2068132451Sroberto
2069132451Sroberto	len = BN_num_bytes(bn);
2070132451Sroberto	ptr = emalloc(len);
2071132451Sroberto	BN_bn2bin(bn, ptr);
2072132451Sroberto	EVP_DigestInit(&ctx, EVP_md5());
2073132451Sroberto	EVP_DigestUpdate(&ctx, ptr, len);
2074132451Sroberto	EVP_DigestFinal(&ctx, dgst, &len);
2075132451Sroberto	BN_bin2bn(dgst, len, bk);
2076285612Sdelphij	free(ptr);
2077132451Sroberto}
2078132451Sroberto
2079132451Sroberto
2080132451Sroberto/*
2081132451Sroberto ***********************************************************************
2082132451Sroberto *								       *
2083132451Sroberto * The following routines implement the Schnorr (IFF) identity scheme  *
2084132451Sroberto *								       *
2085132451Sroberto ***********************************************************************
2086132451Sroberto *
2087132451Sroberto * The Schnorr (IFF) identity scheme is intended for use when
2088285612Sdelphij * certificates are generated by some other trusted certificate
2089285612Sdelphij * authority and the certificate cannot be used to convey public
2090285612Sdelphij * parameters. There are two kinds of files: encrypted server files that
2091285612Sdelphij * contain private and public values and nonencrypted client files that
2092285612Sdelphij * contain only public values. New generations of server files must be
2093285612Sdelphij * securely transmitted to all servers of the group; client files can be
2094285612Sdelphij * distributed by any means. The scheme is self contained and
2095285612Sdelphij * independent of new generations of host keys, sign keys and
2096285612Sdelphij * certificates.
2097132451Sroberto *
2098285612Sdelphij * The IFF values hide in a DSA cuckoo structure which uses the same
2099285612Sdelphij * parameters. The values are used by an identity scheme based on DSA
2100285612Sdelphij * cryptography and described in Stimson p. 285. The p is a 512-bit
2101285612Sdelphij * prime, g a generator of Zp* and q a 160-bit prime that divides p - 1
2102285612Sdelphij * and is a qth root of 1 mod p; that is, g^q = 1 mod p. The TA rolls a
2103285612Sdelphij * private random group key b (0 < b < q) and public key v = g^b, then
2104285612Sdelphij * sends (p, q, g, b) to the servers and (p, q, g, v) to the clients.
2105285612Sdelphij * Alice challenges Bob to confirm identity using the protocol described
2106285612Sdelphij * below.
2107132451Sroberto *
2108132451Sroberto * How it works
2109132451Sroberto *
2110132451Sroberto * The scheme goes like this. Both Alice and Bob have the public primes
2111132451Sroberto * p, q and generator g. The TA gives private key b to Bob and public
2112285612Sdelphij * key v to Alice.
2113132451Sroberto *
2114285612Sdelphij * Alice rolls new random challenge r (o < r < q) and sends to Bob in
2115285612Sdelphij * the IFF request message. Bob rolls new random k (0 < k < q), then
2116285612Sdelphij * computes y = k + b r mod q and x = g^k mod p and sends (y, hash(x))
2117285612Sdelphij * to Alice in the response message. Besides making the response
2118285612Sdelphij * shorter, the hash makes it effectivey impossible for an intruder to
2119285612Sdelphij * solve for b by observing a number of these messages.
2120132451Sroberto *
2121132451Sroberto * Alice receives the response and computes g^y v^r mod p. After a bit
2122132451Sroberto * of algebra, this simplifies to g^k. If the hash of this result
2123132451Sroberto * matches hash(x), Alice knows that Bob has the group key b. The signed
2124132451Sroberto * response binds this knowledge to Bob's private key and the public key
2125132451Sroberto * previously received in his certificate.
2126132451Sroberto *
2127132451Sroberto * crypto_alice - construct Alice's challenge in IFF scheme
2128132451Sroberto *
2129132451Sroberto * Returns
2130132451Sroberto * XEVNT_OK	success
2131285612Sdelphij * XEVNT_ID	bad or missing group key
2132132451Sroberto * XEVNT_PUB	bad or missing public key
2133132451Sroberto */
2134132451Srobertostatic int
2135132451Srobertocrypto_alice(
2136132451Sroberto	struct peer *peer,	/* peer pointer */
2137132451Sroberto	struct value *vp	/* value pointer */
2138132451Sroberto	)
2139132451Sroberto{
2140132451Sroberto	DSA	*dsa;		/* IFF parameters */
2141132451Sroberto	BN_CTX	*bctx;		/* BIGNUM context */
2142132451Sroberto	EVP_MD_CTX ctx;		/* signature context */
2143132451Sroberto	tstamp_t tstamp;
2144132451Sroberto	u_int	len;
2145132451Sroberto
2146132451Sroberto	/*
2147132451Sroberto	 * The identity parameters must have correct format and content.
2148132451Sroberto	 */
2149285612Sdelphij	if (peer->ident_pkey == NULL) {
2150285612Sdelphij		msyslog(LOG_NOTICE, "crypto_alice: scheme unavailable");
2151132451Sroberto		return (XEVNT_ID);
2152285612Sdelphij	}
2153182007Sroberto
2154285612Sdelphij	if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) {
2155285612Sdelphij		msyslog(LOG_NOTICE, "crypto_alice: defective key");
2156132451Sroberto		return (XEVNT_PUB);
2157132451Sroberto	}
2158132451Sroberto
2159132451Sroberto	/*
2160285612Sdelphij	 * Roll new random r (0 < r < q).
2161132451Sroberto	 */
2162132451Sroberto	if (peer->iffval != NULL)
2163132451Sroberto		BN_free(peer->iffval);
2164132451Sroberto	peer->iffval = BN_new();
2165285612Sdelphij	len = BN_num_bytes(dsa->q);
2166285612Sdelphij	BN_rand(peer->iffval, len * 8, -1, 1);	/* r mod q*/
2167285612Sdelphij	bctx = BN_CTX_new();
2168132451Sroberto	BN_mod(peer->iffval, peer->iffval, dsa->q, bctx);
2169132451Sroberto	BN_CTX_free(bctx);
2170132451Sroberto
2171132451Sroberto	/*
2172132451Sroberto	 * Sign and send to Bob. The filestamp is from the local file.
2173132451Sroberto	 */
2174285612Sdelphij	memset(vp, 0, sizeof(struct value));
2175132451Sroberto	tstamp = crypto_time();
2176132451Sroberto	vp->tstamp = htonl(tstamp);
2177285612Sdelphij	vp->fstamp = htonl(peer->ident_pkey->fstamp);
2178132451Sroberto	vp->vallen = htonl(len);
2179132451Sroberto	vp->ptr = emalloc(len);
2180132451Sroberto	BN_bn2bin(peer->iffval, vp->ptr);
2181132451Sroberto	if (tstamp == 0)
2182132451Sroberto		return (XEVNT_OK);
2183182007Sroberto
2184132451Sroberto	vp->sig = emalloc(sign_siglen);
2185132451Sroberto	EVP_SignInit(&ctx, sign_digest);
2186132451Sroberto	EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2187132451Sroberto	EVP_SignUpdate(&ctx, vp->ptr, len);
2188285612Sdelphij	if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
2189289999Sglebius		INSIST(len <= sign_siglen);
2190132451Sroberto		vp->siglen = htonl(len);
2191285612Sdelphij	}
2192132451Sroberto	return (XEVNT_OK);
2193132451Sroberto}
2194132451Sroberto
2195132451Sroberto
2196132451Sroberto/*
2197132451Sroberto * crypto_bob - construct Bob's response to Alice's challenge
2198132451Sroberto *
2199132451Sroberto * Returns
2200132451Sroberto * XEVNT_OK	success
2201285612Sdelphij * XEVNT_ERR	protocol error
2202182007Sroberto * XEVNT_ID	bad or missing group key
2203132451Sroberto */
2204132451Srobertostatic int
2205132451Srobertocrypto_bob(
2206132451Sroberto	struct exten *ep,	/* extension pointer */
2207132451Sroberto	struct value *vp	/* value pointer */
2208132451Sroberto	)
2209132451Sroberto{
2210132451Sroberto	DSA	*dsa;		/* IFF parameters */
2211132451Sroberto	DSA_SIG	*sdsa;		/* DSA signature context fake */
2212132451Sroberto	BN_CTX	*bctx;		/* BIGNUM context */
2213132451Sroberto	EVP_MD_CTX ctx;		/* signature context */
2214132451Sroberto	tstamp_t tstamp;	/* NTP timestamp */
2215132451Sroberto	BIGNUM	*bn, *bk, *r;
2216132451Sroberto	u_char	*ptr;
2217289999Sglebius	u_int	len;		/* extension field value length */
2218132451Sroberto
2219132451Sroberto	/*
2220132451Sroberto	 * If the IFF parameters are not valid, something awful
2221132451Sroberto	 * happened or we are being tormented.
2222132451Sroberto	 */
2223285612Sdelphij	if (iffkey_info == NULL) {
2224285612Sdelphij		msyslog(LOG_NOTICE, "crypto_bob: scheme unavailable");
2225182007Sroberto		return (XEVNT_ID);
2226132451Sroberto	}
2227285612Sdelphij	dsa = iffkey_info->pkey->pkey.dsa;
2228132451Sroberto
2229132451Sroberto	/*
2230132451Sroberto	 * Extract r from the challenge.
2231132451Sroberto	 */
2232289999Sglebius	len = exten_payload_size(ep);
2233289999Sglebius	if (len == 0 || len > MAX_VALLEN)
2234289999Sglebius		return (XEVNT_LEN);
2235289999Sglebius	if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2236285612Sdelphij		msyslog(LOG_ERR, "crypto_bob: %s",
2237132451Sroberto		    ERR_error_string(ERR_get_error(), NULL));
2238182007Sroberto		return (XEVNT_ERR);
2239132451Sroberto	}
2240132451Sroberto
2241132451Sroberto	/*
2242132451Sroberto	 * Bob rolls random k (0 < k < q), computes y = k + b r mod q
2243132451Sroberto	 * and x = g^k mod p, then sends (y, hash(x)) to Alice.
2244132451Sroberto	 */
2245132451Sroberto	bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2246132451Sroberto	sdsa = DSA_SIG_new();
2247289999Sglebius	BN_rand(bk, len * 8, -1, 1);		/* k */
2248132451Sroberto	BN_mod_mul(bn, dsa->priv_key, r, dsa->q, bctx); /* b r mod q */
2249132451Sroberto	BN_add(bn, bn, bk);
2250132451Sroberto	BN_mod(bn, bn, dsa->q, bctx);		/* k + b r mod q */
2251132451Sroberto	sdsa->r = BN_dup(bn);
2252132451Sroberto	BN_mod_exp(bk, dsa->g, bk, dsa->p, bctx); /* g^k mod p */
2253132451Sroberto	bighash(bk, bk);
2254132451Sroberto	sdsa->s = BN_dup(bk);
2255132451Sroberto	BN_CTX_free(bctx);
2256132451Sroberto	BN_free(r); BN_free(bn); BN_free(bk);
2257285612Sdelphij#ifdef DEBUG
2258285612Sdelphij	if (debug > 1)
2259285612Sdelphij		DSA_print_fp(stdout, dsa, 0);
2260285612Sdelphij#endif
2261132451Sroberto
2262132451Sroberto	/*
2263285612Sdelphij	 * Encode the values in ASN.1 and sign. The filestamp is from
2264285612Sdelphij	 * the local file.
2265132451Sroberto	 */
2266289999Sglebius	len = i2d_DSA_SIG(sdsa, NULL);
2267289999Sglebius	if (len == 0) {
2268285612Sdelphij		msyslog(LOG_ERR, "crypto_bob: %s",
2269132451Sroberto		    ERR_error_string(ERR_get_error(), NULL));
2270132451Sroberto		DSA_SIG_free(sdsa);
2271182007Sroberto		return (XEVNT_ERR);
2272132451Sroberto	}
2273289999Sglebius	if (len > MAX_VALLEN) {
2274289999Sglebius		msyslog(LOG_ERR, "crypto_bob: signature is too big: %u",
2275289999Sglebius		    len);
2276281230Sdelphij		DSA_SIG_free(sdsa);
2277281230Sdelphij		return (XEVNT_LEN);
2278281230Sdelphij	}
2279281230Sdelphij	memset(vp, 0, sizeof(struct value));
2280281230Sdelphij	tstamp = crypto_time();
2281281230Sdelphij	vp->tstamp = htonl(tstamp);
2282285612Sdelphij	vp->fstamp = htonl(iffkey_info->fstamp);
2283289999Sglebius	vp->vallen = htonl(len);
2284289999Sglebius	ptr = emalloc(len);
2285132451Sroberto	vp->ptr = ptr;
2286132451Sroberto	i2d_DSA_SIG(sdsa, &ptr);
2287132451Sroberto	DSA_SIG_free(sdsa);
2288132451Sroberto	if (tstamp == 0)
2289132451Sroberto		return (XEVNT_OK);
2290182007Sroberto
2291281230Sdelphij	/* XXX: more validation to make sure the sign fits... */
2292132451Sroberto	vp->sig = emalloc(sign_siglen);
2293132451Sroberto	EVP_SignInit(&ctx, sign_digest);
2294132451Sroberto	EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2295289999Sglebius	EVP_SignUpdate(&ctx, vp->ptr, len);
2296289999Sglebius	if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
2297289999Sglebius		INSIST(len <= sign_siglen);
2298289999Sglebius		vp->siglen = htonl(len);
2299285612Sdelphij	}
2300132451Sroberto	return (XEVNT_OK);
2301132451Sroberto}
2302132451Sroberto
2303132451Sroberto
2304132451Sroberto/*
2305132451Sroberto * crypto_iff - verify Bob's response to Alice's challenge
2306132451Sroberto *
2307132451Sroberto * Returns
2308132451Sroberto * XEVNT_OK	success
2309285612Sdelphij * XEVNT_FSP	bad filestamp
2310285612Sdelphij * XEVNT_ID	bad or missing group key
2311132451Sroberto * XEVNT_PUB	bad or missing public key
2312132451Sroberto */
2313132451Srobertoint
2314132451Srobertocrypto_iff(
2315132451Sroberto	struct exten *ep,	/* extension pointer */
2316132451Sroberto	struct peer *peer	/* peer structure pointer */
2317132451Sroberto	)
2318132451Sroberto{
2319132451Sroberto	DSA	*dsa;		/* IFF parameters */
2320132451Sroberto	BN_CTX	*bctx;		/* BIGNUM context */
2321132451Sroberto	DSA_SIG	*sdsa;		/* DSA parameters */
2322132451Sroberto	BIGNUM	*bn, *bk;
2323132451Sroberto	u_int	len;
2324285612Sdelphij	const u_char *ptr;
2325132451Sroberto	int	temp;
2326132451Sroberto
2327132451Sroberto	/*
2328132451Sroberto	 * If the IFF parameters are not valid or no challenge was sent,
2329132451Sroberto	 * something awful happened or we are being tormented.
2330132451Sroberto	 */
2331132451Sroberto	if (peer->ident_pkey == NULL) {
2332285612Sdelphij		msyslog(LOG_NOTICE, "crypto_iff: scheme unavailable");
2333182007Sroberto		return (XEVNT_ID);
2334132451Sroberto	}
2335285612Sdelphij	if (ntohl(ep->fstamp) != peer->ident_pkey->fstamp) {
2336285612Sdelphij		msyslog(LOG_NOTICE, "crypto_iff: invalid filestamp %u",
2337132451Sroberto		    ntohl(ep->fstamp));
2338132451Sroberto		return (XEVNT_FSP);
2339132451Sroberto	}
2340285612Sdelphij	if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) {
2341285612Sdelphij		msyslog(LOG_NOTICE, "crypto_iff: defective key");
2342132451Sroberto		return (XEVNT_PUB);
2343132451Sroberto	}
2344132451Sroberto	if (peer->iffval == NULL) {
2345285612Sdelphij		msyslog(LOG_NOTICE, "crypto_iff: missing challenge");
2346182007Sroberto		return (XEVNT_ID);
2347132451Sroberto	}
2348132451Sroberto
2349132451Sroberto	/*
2350132451Sroberto	 * Extract the k + b r and g^k values from the response.
2351132451Sroberto	 */
2352132451Sroberto	bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2353132451Sroberto	len = ntohl(ep->vallen);
2354285612Sdelphij	ptr = (u_char *)ep->pkt;
2355132451Sroberto	if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2356285612Sdelphij		BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
2357285612Sdelphij		msyslog(LOG_ERR, "crypto_iff: %s",
2358132451Sroberto		    ERR_error_string(ERR_get_error(), NULL));
2359182007Sroberto		return (XEVNT_ERR);
2360132451Sroberto	}
2361132451Sroberto
2362132451Sroberto	/*
2363132451Sroberto	 * Compute g^(k + b r) g^(q - b)r mod p.
2364132451Sroberto	 */
2365132451Sroberto	BN_mod_exp(bn, dsa->pub_key, peer->iffval, dsa->p, bctx);
2366132451Sroberto	BN_mod_exp(bk, dsa->g, sdsa->r, dsa->p, bctx);
2367132451Sroberto	BN_mod_mul(bn, bn, bk, dsa->p, bctx);
2368132451Sroberto
2369132451Sroberto	/*
2370132451Sroberto	 * Verify the hash of the result matches hash(x).
2371132451Sroberto	 */
2372132451Sroberto	bighash(bn, bn);
2373132451Sroberto	temp = BN_cmp(bn, sdsa->s);
2374132451Sroberto	BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
2375132451Sroberto	BN_free(peer->iffval);
2376132451Sroberto	peer->iffval = NULL;
2377132451Sroberto	DSA_SIG_free(sdsa);
2378132451Sroberto	if (temp == 0)
2379132451Sroberto		return (XEVNT_OK);
2380182007Sroberto
2381285612Sdelphij	msyslog(LOG_NOTICE, "crypto_iff: identity not verified");
2382285612Sdelphij	return (XEVNT_ID);
2383132451Sroberto}
2384132451Sroberto
2385132451Sroberto
2386132451Sroberto/*
2387132451Sroberto ***********************************************************************
2388132451Sroberto *								       *
2389132451Sroberto * The following routines implement the Guillou-Quisquater (GQ)        *
2390132451Sroberto * identity scheme                                                     *
2391132451Sroberto *								       *
2392132451Sroberto ***********************************************************************
2393132451Sroberto *
2394132451Sroberto * The Guillou-Quisquater (GQ) identity scheme is intended for use when
2395285612Sdelphij * the certificate can be used to convey public parameters. The scheme
2396285612Sdelphij * uses a X509v3 certificate extension field do convey the public key of
2397285612Sdelphij * a private key known only to servers. There are two kinds of files:
2398285612Sdelphij * encrypted server files that contain private and public values and
2399285612Sdelphij * nonencrypted client files that contain only public values. New
2400285612Sdelphij * generations of server files must be securely transmitted to all
2401285612Sdelphij * servers of the group; client files can be distributed by any means.
2402285612Sdelphij * The scheme is self contained and independent of new generations of
2403285612Sdelphij * host keys and sign keys. The scheme is self contained and independent
2404285612Sdelphij * of new generations of host keys and sign keys.
2405132451Sroberto *
2406285612Sdelphij * The GQ parameters hide in a RSA cuckoo structure which uses the same
2407285612Sdelphij * parameters. The values are used by an identity scheme based on RSA
2408285612Sdelphij * cryptography and described in Stimson p. 300 (with errors). The 512-
2409285612Sdelphij * bit public modulus is n = p q, where p and q are secret large primes.
2410285612Sdelphij * The TA rolls private random group key b as RSA exponent. These values
2411285612Sdelphij * are known to all group members.
2412132451Sroberto *
2413285612Sdelphij * When rolling new certificates, a server recomputes the private and
2414132451Sroberto * public keys. The private key u is a random roll, while the public key
2415132451Sroberto * is the inverse obscured by the group key v = (u^-1)^b. These values
2416132451Sroberto * replace the private and public keys normally generated by the RSA
2417132451Sroberto * scheme. Alice challenges Bob to confirm identity using the protocol
2418132451Sroberto * described below.
2419132451Sroberto *
2420132451Sroberto * How it works
2421132451Sroberto *
2422132451Sroberto * The scheme goes like this. Both Alice and Bob have the same modulus n
2423132451Sroberto * and some random b as the group key. These values are computed and
2424132451Sroberto * distributed in advance via secret means, although only the group key
2425132451Sroberto * b is truly secret. Each has a private random private key u and public
2426132451Sroberto * key (u^-1)^b, although not necessarily the same ones. Bob and Alice
2427132451Sroberto * can regenerate the key pair from time to time without affecting
2428132451Sroberto * operations. The public key is conveyed on the certificate in an
2429132451Sroberto * extension field; the private key is never revealed.
2430132451Sroberto *
2431132451Sroberto * Alice rolls new random challenge r and sends to Bob in the GQ
2432132451Sroberto * request message. Bob rolls new random k, then computes y = k u^r mod
2433132451Sroberto * n and x = k^b mod n and sends (y, hash(x)) to Alice in the response
2434132451Sroberto * message. Besides making the response shorter, the hash makes it
2435132451Sroberto * effectivey impossible for an intruder to solve for b by observing
2436132451Sroberto * a number of these messages.
2437132451Sroberto *
2438132451Sroberto * Alice receives the response and computes y^b v^r mod n. After a bit
2439132451Sroberto * of algebra, this simplifies to k^b. If the hash of this result
2440132451Sroberto * matches hash(x), Alice knows that Bob has the group key b. The signed
2441132451Sroberto * response binds this knowledge to Bob's private key and the public key
2442132451Sroberto * previously received in his certificate.
2443132451Sroberto *
2444132451Sroberto * crypto_alice2 - construct Alice's challenge in GQ scheme
2445132451Sroberto *
2446132451Sroberto * Returns
2447132451Sroberto * XEVNT_OK	success
2448285612Sdelphij * XEVNT_ID	bad or missing group key
2449132451Sroberto * XEVNT_PUB	bad or missing public key
2450132451Sroberto */
2451132451Srobertostatic int
2452132451Srobertocrypto_alice2(
2453132451Sroberto	struct peer *peer,	/* peer pointer */
2454132451Sroberto	struct value *vp	/* value pointer */
2455132451Sroberto	)
2456132451Sroberto{
2457132451Sroberto	RSA	*rsa;		/* GQ parameters */
2458132451Sroberto	BN_CTX	*bctx;		/* BIGNUM context */
2459132451Sroberto	EVP_MD_CTX ctx;		/* signature context */
2460132451Sroberto	tstamp_t tstamp;
2461132451Sroberto	u_int	len;
2462132451Sroberto
2463132451Sroberto	/*
2464132451Sroberto	 * The identity parameters must have correct format and content.
2465132451Sroberto	 */
2466132451Sroberto	if (peer->ident_pkey == NULL)
2467132451Sroberto		return (XEVNT_ID);
2468182007Sroberto
2469285612Sdelphij	if ((rsa = peer->ident_pkey->pkey->pkey.rsa) == NULL) {
2470285612Sdelphij		msyslog(LOG_NOTICE, "crypto_alice2: defective key");
2471132451Sroberto		return (XEVNT_PUB);
247282498Sroberto	}
247382498Sroberto
247482498Sroberto	/*
2475285612Sdelphij	 * Roll new random r (0 < r < n).
247682498Sroberto	 */
2477132451Sroberto	if (peer->iffval != NULL)
2478132451Sroberto		BN_free(peer->iffval);
2479132451Sroberto	peer->iffval = BN_new();
2480285612Sdelphij	len = BN_num_bytes(rsa->n);
2481132451Sroberto	BN_rand(peer->iffval, len * 8, -1, 1);	/* r mod n */
2482285612Sdelphij	bctx = BN_CTX_new();
2483132451Sroberto	BN_mod(peer->iffval, peer->iffval, rsa->n, bctx);
2484132451Sroberto	BN_CTX_free(bctx);
2485132451Sroberto
2486132451Sroberto	/*
2487132451Sroberto	 * Sign and send to Bob. The filestamp is from the local file.
2488132451Sroberto	 */
2489285612Sdelphij	memset(vp, 0, sizeof(struct value));
2490132451Sroberto	tstamp = crypto_time();
2491132451Sroberto	vp->tstamp = htonl(tstamp);
2492285612Sdelphij	vp->fstamp = htonl(peer->ident_pkey->fstamp);
2493132451Sroberto	vp->vallen = htonl(len);
2494132451Sroberto	vp->ptr = emalloc(len);
2495132451Sroberto	BN_bn2bin(peer->iffval, vp->ptr);
2496132451Sroberto	if (tstamp == 0)
2497132451Sroberto		return (XEVNT_OK);
2498182007Sroberto
2499132451Sroberto	vp->sig = emalloc(sign_siglen);
2500132451Sroberto	EVP_SignInit(&ctx, sign_digest);
2501132451Sroberto	EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2502132451Sroberto	EVP_SignUpdate(&ctx, vp->ptr, len);
2503285612Sdelphij	if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
2504289999Sglebius		INSIST(len <= sign_siglen);
2505132451Sroberto		vp->siglen = htonl(len);
2506285612Sdelphij	}
2507132451Sroberto	return (XEVNT_OK);
2508132451Sroberto}
2509132451Sroberto
2510132451Sroberto
2511132451Sroberto/*
2512132451Sroberto * crypto_bob2 - construct Bob's response to Alice's challenge
2513132451Sroberto *
2514132451Sroberto * Returns
2515132451Sroberto * XEVNT_OK	success
2516285612Sdelphij * XEVNT_ERR	protocol error
2517182007Sroberto * XEVNT_ID	bad or missing group key
2518132451Sroberto */
2519132451Srobertostatic int
2520132451Srobertocrypto_bob2(
2521132451Sroberto	struct exten *ep,	/* extension pointer */
2522132451Sroberto	struct value *vp	/* value pointer */
2523132451Sroberto	)
2524132451Sroberto{
2525132451Sroberto	RSA	*rsa;		/* GQ parameters */
2526132451Sroberto	DSA_SIG	*sdsa;		/* DSA parameters */
2527132451Sroberto	BN_CTX	*bctx;		/* BIGNUM context */
2528132451Sroberto	EVP_MD_CTX ctx;		/* signature context */
2529132451Sroberto	tstamp_t tstamp;	/* NTP timestamp */
2530132451Sroberto	BIGNUM	*r, *k, *g, *y;
2531132451Sroberto	u_char	*ptr;
2532132451Sroberto	u_int	len;
2533285612Sdelphij	int	s_len;
2534132451Sroberto
2535132451Sroberto	/*
2536132451Sroberto	 * If the GQ parameters are not valid, something awful
2537132451Sroberto	 * happened or we are being tormented.
2538132451Sroberto	 */
2539285612Sdelphij	if (gqkey_info == NULL) {
2540285612Sdelphij		msyslog(LOG_NOTICE, "crypto_bob2: scheme unavailable");
2541182007Sroberto		return (XEVNT_ID);
254282498Sroberto	}
2543285612Sdelphij	rsa = gqkey_info->pkey->pkey.rsa;
254482498Sroberto
254582498Sroberto	/*
2546132451Sroberto	 * Extract r from the challenge.
254782498Sroberto	 */
2548289999Sglebius	len = exten_payload_size(ep);
2549289999Sglebius	if (len == 0 || len > MAX_VALLEN)
2550289999Sglebius		return (XEVNT_LEN);
2551132451Sroberto	if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2552285612Sdelphij		msyslog(LOG_ERR, "crypto_bob2: %s",
2553132451Sroberto		    ERR_error_string(ERR_get_error(), NULL));
2554182007Sroberto		return (XEVNT_ERR);
2555132451Sroberto	}
2556132451Sroberto
2557132451Sroberto	/*
2558132451Sroberto	 * Bob rolls random k (0 < k < n), computes y = k u^r mod n and
2559132451Sroberto	 * x = k^b mod n, then sends (y, hash(x)) to Alice.
2560132451Sroberto	 */
2561132451Sroberto	bctx = BN_CTX_new(); k = BN_new(); g = BN_new(); y = BN_new();
2562132451Sroberto	sdsa = DSA_SIG_new();
2563132451Sroberto	BN_rand(k, len * 8, -1, 1);		/* k */
2564132451Sroberto	BN_mod(k, k, rsa->n, bctx);
2565132451Sroberto	BN_mod_exp(y, rsa->p, r, rsa->n, bctx); /* u^r mod n */
2566132451Sroberto	BN_mod_mul(y, k, y, rsa->n, bctx);	/* k u^r mod n */
2567132451Sroberto	sdsa->r = BN_dup(y);
2568132451Sroberto	BN_mod_exp(g, k, rsa->e, rsa->n, bctx); /* k^b mod n */
2569132451Sroberto	bighash(g, g);
2570132451Sroberto	sdsa->s = BN_dup(g);
2571132451Sroberto	BN_CTX_free(bctx);
2572132451Sroberto	BN_free(r); BN_free(k); BN_free(g); BN_free(y);
2573285612Sdelphij#ifdef DEBUG
2574285612Sdelphij	if (debug > 1)
2575285612Sdelphij		RSA_print_fp(stdout, rsa, 0);
2576285612Sdelphij#endif
2577132451Sroberto
2578132451Sroberto	/*
2579285612Sdelphij	 * Encode the values in ASN.1 and sign. The filestamp is from
2580285612Sdelphij	 * the local file.
2581132451Sroberto	 */
2582285612Sdelphij	len = s_len = i2d_DSA_SIG(sdsa, NULL);
2583285612Sdelphij	if (s_len <= 0) {
2584285612Sdelphij		msyslog(LOG_ERR, "crypto_bob2: %s",
2585132451Sroberto		    ERR_error_string(ERR_get_error(), NULL));
2586132451Sroberto		DSA_SIG_free(sdsa);
2587182007Sroberto		return (XEVNT_ERR);
2588132451Sroberto	}
2589285612Sdelphij	memset(vp, 0, sizeof(struct value));
2590285612Sdelphij	tstamp = crypto_time();
2591285612Sdelphij	vp->tstamp = htonl(tstamp);
2592285612Sdelphij	vp->fstamp = htonl(gqkey_info->fstamp);
2593132451Sroberto	vp->vallen = htonl(len);
2594132451Sroberto	ptr = emalloc(len);
2595132451Sroberto	vp->ptr = ptr;
2596132451Sroberto	i2d_DSA_SIG(sdsa, &ptr);
2597132451Sroberto	DSA_SIG_free(sdsa);
2598132451Sroberto	if (tstamp == 0)
2599132451Sroberto		return (XEVNT_OK);
2600182007Sroberto
2601132451Sroberto	vp->sig = emalloc(sign_siglen);
2602132451Sroberto	EVP_SignInit(&ctx, sign_digest);
2603132451Sroberto	EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2604132451Sroberto	EVP_SignUpdate(&ctx, vp->ptr, len);
2605285612Sdelphij	if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
2606289999Sglebius		INSIST(len <= sign_siglen);
2607132451Sroberto		vp->siglen = htonl(len);
2608285612Sdelphij	}
2609132451Sroberto	return (XEVNT_OK);
2610132451Sroberto}
2611132451Sroberto
2612132451Sroberto
2613132451Sroberto/*
2614132451Sroberto * crypto_gq - verify Bob's response to Alice's challenge
2615132451Sroberto *
2616132451Sroberto * Returns
2617132451Sroberto * XEVNT_OK	success
2618182007Sroberto * XEVNT_ERR	protocol error
2619132451Sroberto * XEVNT_FSP	bad filestamp
2620285612Sdelphij * XEVNT_ID	bad or missing group keys
2621285612Sdelphij * XEVNT_PUB	bad or missing public key
2622132451Sroberto */
2623132451Srobertoint
2624132451Srobertocrypto_gq(
2625132451Sroberto	struct exten *ep,	/* extension pointer */
2626132451Sroberto	struct peer *peer	/* peer structure pointer */
2627132451Sroberto	)
2628132451Sroberto{
2629132451Sroberto	RSA	*rsa;		/* GQ parameters */
2630132451Sroberto	BN_CTX	*bctx;		/* BIGNUM context */
2631132451Sroberto	DSA_SIG	*sdsa;		/* RSA signature context fake */
2632132451Sroberto	BIGNUM	*y, *v;
2633285612Sdelphij	const u_char *ptr;
2634285612Sdelphij	long	len;
2635285612Sdelphij	u_int	temp;
2636132451Sroberto
2637132451Sroberto	/*
2638132451Sroberto	 * If the GQ parameters are not valid or no challenge was sent,
2639285612Sdelphij	 * something awful happened or we are being tormented. Note that
2640285612Sdelphij	 * the filestamp on the local key file can be greater than on
2641285612Sdelphij	 * the remote parameter file if the keys have been refreshed.
2642132451Sroberto	 */
2643132451Sroberto	if (peer->ident_pkey == NULL) {
2644285612Sdelphij		msyslog(LOG_NOTICE, "crypto_gq: scheme unavailable");
2645182007Sroberto		return (XEVNT_ID);
2646132451Sroberto	}
2647285612Sdelphij	if (ntohl(ep->fstamp) < peer->ident_pkey->fstamp) {
2648285612Sdelphij		msyslog(LOG_NOTICE, "crypto_gq: invalid filestamp %u",
2649132451Sroberto		    ntohl(ep->fstamp));
2650132451Sroberto		return (XEVNT_FSP);
2651132451Sroberto	}
2652285612Sdelphij	if ((rsa = peer->ident_pkey->pkey->pkey.rsa) == NULL) {
2653285612Sdelphij		msyslog(LOG_NOTICE, "crypto_gq: defective key");
2654132451Sroberto		return (XEVNT_PUB);
2655132451Sroberto	}
2656132451Sroberto	if (peer->iffval == NULL) {
2657285612Sdelphij		msyslog(LOG_NOTICE, "crypto_gq: missing challenge");
2658182007Sroberto		return (XEVNT_ID);
2659132451Sroberto	}
2660132451Sroberto
2661132451Sroberto	/*
2662132451Sroberto	 * Extract the y = k u^r and hash(x = k^b) values from the
2663132451Sroberto	 * response.
2664132451Sroberto	 */
2665132451Sroberto	bctx = BN_CTX_new(); y = BN_new(); v = BN_new();
2666132451Sroberto	len = ntohl(ep->vallen);
2667285612Sdelphij	ptr = (u_char *)ep->pkt;
2668132451Sroberto	if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2669285612Sdelphij		BN_CTX_free(bctx); BN_free(y); BN_free(v);
2670285612Sdelphij		msyslog(LOG_ERR, "crypto_gq: %s",
2671132451Sroberto		    ERR_error_string(ERR_get_error(), NULL));
2672182007Sroberto		return (XEVNT_ERR);
2673132451Sroberto	}
2674132451Sroberto
2675132451Sroberto	/*
2676132451Sroberto	 * Compute v^r y^b mod n.
2677132451Sroberto	 */
2678285612Sdelphij	if (peer->grpkey == NULL) {
2679285612Sdelphij		msyslog(LOG_NOTICE, "crypto_gq: missing group key");
2680285612Sdelphij		return (XEVNT_ID);
2681285612Sdelphij	}
2682132451Sroberto	BN_mod_exp(v, peer->grpkey, peer->iffval, rsa->n, bctx);
2683132451Sroberto						/* v^r mod n */
2684132451Sroberto	BN_mod_exp(y, sdsa->r, rsa->e, rsa->n, bctx); /* y^b mod n */
2685132451Sroberto	BN_mod_mul(y, v, y, rsa->n, bctx);	/* v^r y^b mod n */
2686132451Sroberto
2687132451Sroberto	/*
2688132451Sroberto	 * Verify the hash of the result matches hash(x).
2689132451Sroberto	 */
2690132451Sroberto	bighash(y, y);
2691132451Sroberto	temp = BN_cmp(y, sdsa->s);
2692132451Sroberto	BN_CTX_free(bctx); BN_free(y); BN_free(v);
2693132451Sroberto	BN_free(peer->iffval);
2694132451Sroberto	peer->iffval = NULL;
2695132451Sroberto	DSA_SIG_free(sdsa);
2696132451Sroberto	if (temp == 0)
2697132451Sroberto		return (XEVNT_OK);
2698182007Sroberto
2699285612Sdelphij	msyslog(LOG_NOTICE, "crypto_gq: identity not verified");
2700285612Sdelphij	return (XEVNT_ID);
2701132451Sroberto}
2702132451Sroberto
2703132451Sroberto
2704132451Sroberto/*
2705132451Sroberto ***********************************************************************
2706132451Sroberto *								       *
2707132451Sroberto * The following routines implement the Mu-Varadharajan (MV) identity  *
2708132451Sroberto * scheme                                                              *
2709132451Sroberto *								       *
2710132451Sroberto ***********************************************************************
2711285612Sdelphij *
2712132451Sroberto * The Mu-Varadharajan (MV) cryptosystem was originally intended when
2713132451Sroberto * servers broadcast messages to clients, but clients never send
2714132451Sroberto * messages to servers. There is one encryption key for the server and a
2715132451Sroberto * separate decryption key for each client. It operated something like a
2716132451Sroberto * pay-per-view satellite broadcasting system where the session key is
2717132451Sroberto * encrypted by the broadcaster and the decryption keys are held in a
2718132451Sroberto * tamperproof set-top box.
2719132451Sroberto *
2720132451Sroberto * The MV parameters and private encryption key hide in a DSA cuckoo
2721132451Sroberto * structure which uses the same parameters, but generated in a
2722132451Sroberto * different way. The values are used in an encryption scheme similar to
2723132451Sroberto * El Gamal cryptography and a polynomial formed from the expansion of
2724132451Sroberto * product terms (x - x[j]), as described in Mu, Y., and V.
2725132451Sroberto * Varadharajan: Robust and Secure Broadcasting, Proc. Indocrypt 2001,
2726132451Sroberto * 223-231. The paper has significant errors and serious omissions.
2727132451Sroberto *
2728285612Sdelphij * Let q be the product of n distinct primes s1[j] (j = 1...n), where
2729285612Sdelphij * each s1[j] has m significant bits. Let p be a prime p = 2 * q + 1, so
2730285612Sdelphij * that q and each s1[j] divide p - 1 and p has M = n * m + 1
2731285612Sdelphij * significant bits. Let g be a generator of Zp; that is, gcd(g, p - 1)
2732285612Sdelphij * = 1 and g^q = 1 mod p. We do modular arithmetic over Zq and then
2733285612Sdelphij * project into Zp* as exponents of g. Sometimes we have to compute an
2734285612Sdelphij * inverse b^-1 of random b in Zq, but for that purpose we require
2735285612Sdelphij * gcd(b, q) = 1. We expect M to be in the 500-bit range and n
2736285612Sdelphij * relatively small, like 30. These are the parameters of the scheme and
2737285612Sdelphij * they are expensive to compute.
2738132451Sroberto *
2739132451Sroberto * We set up an instance of the scheme as follows. A set of random
2740132451Sroberto * values x[j] mod q (j = 1...n), are generated as the zeros of a
2741132451Sroberto * polynomial of order n. The product terms (x - x[j]) are expanded to
2742132451Sroberto * form coefficients a[i] mod q (i = 0...n) in powers of x. These are
2743132451Sroberto * used as exponents of the generator g mod p to generate the private
2744132451Sroberto * encryption key A. The pair (gbar, ghat) of public server keys and the
2745132451Sroberto * pairs (xbar[j], xhat[j]) (j = 1...n) of private client keys are used
2746132451Sroberto * to construct the decryption keys. The devil is in the details.
2747132451Sroberto *
2748285612Sdelphij * This routine generates a private server encryption file including the
2749285612Sdelphij * private encryption key E and partial decryption keys gbar and ghat.
2750285612Sdelphij * It then generates public client decryption files including the public
2751285612Sdelphij * keys xbar[j] and xhat[j] for each client j. The partial decryption
2752285612Sdelphij * files are used to compute the inverse of E. These values are suitably
2753285612Sdelphij * blinded so secrets are not revealed.
2754285612Sdelphij *
2755132451Sroberto * The distinguishing characteristic of this scheme is the capability to
2756132451Sroberto * revoke keys. Included in the calculation of E, gbar and ghat is the
2757285612Sdelphij * product s = prod(s1[j]) (j = 1...n) above. If the factor s1[j] is
2758132451Sroberto * subsequently removed from the product and E, gbar and ghat
2759132451Sroberto * recomputed, the jth client will no longer be able to compute E^-1 and
2760285612Sdelphij * thus unable to decrypt the messageblock.
2761132451Sroberto *
2762132451Sroberto * How it works
2763132451Sroberto *
2764285612Sdelphij * The scheme goes like this. Bob has the server values (p, E, q, gbar,
2765285612Sdelphij * ghat) and Alice has the client values (p, xbar, xhat).
2766132451Sroberto *
2767285612Sdelphij * Alice rolls new random nonce r mod p and sends to Bob in the MV
2768285612Sdelphij * request message. Bob rolls random nonce k mod q, encrypts y = r E^k
2769285612Sdelphij * mod p and sends (y, gbar^k, ghat^k) to Alice.
2770132451Sroberto *
2771285612Sdelphij * Alice receives the response and computes the inverse (E^k)^-1 from
2772285612Sdelphij * the partial decryption keys gbar^k, ghat^k, xbar and xhat. She then
2773285612Sdelphij * decrypts y and verifies it matches the original r. The signed
2774285612Sdelphij * response binds this knowledge to Bob's private key and the public key
2775285612Sdelphij * previously received in his certificate.
2776132451Sroberto *
2777132451Sroberto * crypto_alice3 - construct Alice's challenge in MV scheme
2778132451Sroberto *
2779132451Sroberto * Returns
2780132451Sroberto * XEVNT_OK	success
2781285612Sdelphij * XEVNT_ID	bad or missing group key
2782132451Sroberto * XEVNT_PUB	bad or missing public key
2783132451Sroberto */
2784132451Srobertostatic int
2785132451Srobertocrypto_alice3(
2786132451Sroberto	struct peer *peer,	/* peer pointer */
2787132451Sroberto	struct value *vp	/* value pointer */
2788132451Sroberto	)
2789132451Sroberto{
2790132451Sroberto	DSA	*dsa;		/* MV parameters */
2791132451Sroberto	BN_CTX	*bctx;		/* BIGNUM context */
2792132451Sroberto	EVP_MD_CTX ctx;		/* signature context */
2793132451Sroberto	tstamp_t tstamp;
2794132451Sroberto	u_int	len;
2795132451Sroberto
2796132451Sroberto	/*
2797132451Sroberto	 * The identity parameters must have correct format and content.
2798132451Sroberto	 */
2799132451Sroberto	if (peer->ident_pkey == NULL)
2800132451Sroberto		return (XEVNT_ID);
2801182007Sroberto
2802285612Sdelphij	if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) {
2803285612Sdelphij		msyslog(LOG_NOTICE, "crypto_alice3: defective key");
2804132451Sroberto		return (XEVNT_PUB);
280582498Sroberto	}
280682498Sroberto
280782498Sroberto	/*
2808285612Sdelphij	 * Roll new random r (0 < r < q).
280982498Sroberto	 */
2810132451Sroberto	if (peer->iffval != NULL)
2811132451Sroberto		BN_free(peer->iffval);
2812132451Sroberto	peer->iffval = BN_new();
2813285612Sdelphij	len = BN_num_bytes(dsa->p);
2814285612Sdelphij	BN_rand(peer->iffval, len * 8, -1, 1);	/* r mod p */
2815285612Sdelphij	bctx = BN_CTX_new();
2816132451Sroberto	BN_mod(peer->iffval, peer->iffval, dsa->p, bctx);
2817132451Sroberto	BN_CTX_free(bctx);
2818132451Sroberto
2819132451Sroberto	/*
2820132451Sroberto	 * Sign and send to Bob. The filestamp is from the local file.
2821132451Sroberto	 */
2822285612Sdelphij	memset(vp, 0, sizeof(struct value));
2823132451Sroberto	tstamp = crypto_time();
2824132451Sroberto	vp->tstamp = htonl(tstamp);
2825285612Sdelphij	vp->fstamp = htonl(peer->ident_pkey->fstamp);
2826132451Sroberto	vp->vallen = htonl(len);
2827132451Sroberto	vp->ptr = emalloc(len);
2828132451Sroberto	BN_bn2bin(peer->iffval, vp->ptr);
2829132451Sroberto	if (tstamp == 0)
2830132451Sroberto		return (XEVNT_OK);
2831182007Sroberto
2832132451Sroberto	vp->sig = emalloc(sign_siglen);
2833132451Sroberto	EVP_SignInit(&ctx, sign_digest);
2834132451Sroberto	EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2835132451Sroberto	EVP_SignUpdate(&ctx, vp->ptr, len);
2836285612Sdelphij	if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
2837289999Sglebius		INSIST(len <= sign_siglen);
2838132451Sroberto		vp->siglen = htonl(len);
2839285612Sdelphij	}
2840132451Sroberto	return (XEVNT_OK);
2841132451Sroberto}
2842132451Sroberto
2843132451Sroberto
2844132451Sroberto/*
2845132451Sroberto * crypto_bob3 - construct Bob's response to Alice's challenge
2846132451Sroberto *
2847132451Sroberto * Returns
2848132451Sroberto * XEVNT_OK	success
2849182007Sroberto * XEVNT_ERR	protocol error
2850132451Sroberto */
2851132451Srobertostatic int
2852132451Srobertocrypto_bob3(
2853132451Sroberto	struct exten *ep,	/* extension pointer */
2854132451Sroberto	struct value *vp	/* value pointer */
2855132451Sroberto	)
2856132451Sroberto{
2857132451Sroberto	DSA	*dsa;		/* MV parameters */
2858132451Sroberto	DSA	*sdsa;		/* DSA signature context fake */
2859132451Sroberto	BN_CTX	*bctx;		/* BIGNUM context */
2860132451Sroberto	EVP_MD_CTX ctx;		/* signature context */
2861132451Sroberto	tstamp_t tstamp;	/* NTP timestamp */
2862132451Sroberto	BIGNUM	*r, *k, *u;
2863132451Sroberto	u_char	*ptr;
2864132451Sroberto	u_int	len;
2865132451Sroberto
2866132451Sroberto	/*
2867132451Sroberto	 * If the MV parameters are not valid, something awful
2868132451Sroberto	 * happened or we are being tormented.
2869132451Sroberto	 */
2870285612Sdelphij	if (mvkey_info == NULL) {
2871285612Sdelphij		msyslog(LOG_NOTICE, "crypto_bob3: scheme unavailable");
2872182007Sroberto		return (XEVNT_ID);
287382498Sroberto	}
2874285612Sdelphij	dsa = mvkey_info->pkey->pkey.dsa;
2875132451Sroberto
2876132451Sroberto	/*
2877132451Sroberto	 * Extract r from the challenge.
2878132451Sroberto	 */
2879289999Sglebius	len = exten_payload_size(ep);
2880289999Sglebius	if (len == 0 || len > MAX_VALLEN)
2881289999Sglebius		return (XEVNT_LEN);
2882132451Sroberto	if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2883285612Sdelphij		msyslog(LOG_ERR, "crypto_bob3: %s",
2884132451Sroberto		    ERR_error_string(ERR_get_error(), NULL));
2885182007Sroberto		return (XEVNT_ERR);
2886132451Sroberto	}
2887132451Sroberto
2888132451Sroberto	/*
2889132451Sroberto	 * Bob rolls random k (0 < k < q), making sure it is not a
2890285612Sdelphij	 * factor of q. He then computes y = r A^k and sends (y, gbar^k,
2891285612Sdelphij	 * and ghat^k) to Alice.
2892132451Sroberto	 */
2893132451Sroberto	bctx = BN_CTX_new(); k = BN_new(); u = BN_new();
2894132451Sroberto	sdsa = DSA_new();
2895132451Sroberto	sdsa->p = BN_new(); sdsa->q = BN_new(); sdsa->g = BN_new();
2896132451Sroberto	while (1) {
2897132451Sroberto		BN_rand(k, BN_num_bits(dsa->q), 0, 0);
2898132451Sroberto		BN_mod(k, k, dsa->q, bctx);
2899132451Sroberto		BN_gcd(u, k, dsa->q, bctx);
2900132451Sroberto		if (BN_is_one(u))
2901132451Sroberto			break;
2902132451Sroberto	}
2903285612Sdelphij	BN_mod_exp(u, dsa->g, k, dsa->p, bctx); /* A^k r */
2904285612Sdelphij	BN_mod_mul(sdsa->p, u, r, dsa->p, bctx);
2905132451Sroberto	BN_mod_exp(sdsa->q, dsa->priv_key, k, dsa->p, bctx); /* gbar */
2906132451Sroberto	BN_mod_exp(sdsa->g, dsa->pub_key, k, dsa->p, bctx); /* ghat */
2907132451Sroberto	BN_CTX_free(bctx); BN_free(k); BN_free(r); BN_free(u);
2908285612Sdelphij#ifdef DEBUG
2909285612Sdelphij	if (debug > 1)
2910285612Sdelphij		DSA_print_fp(stdout, sdsa, 0);
2911285612Sdelphij#endif
2912132451Sroberto
2913132451Sroberto	/*
2914285612Sdelphij	 * Encode the values in ASN.1 and sign. The filestamp is from
2915285612Sdelphij	 * the local file.
2916132451Sroberto	 */
2917285612Sdelphij	memset(vp, 0, sizeof(struct value));
2918132451Sroberto	tstamp = crypto_time();
2919132451Sroberto	vp->tstamp = htonl(tstamp);
2920285612Sdelphij	vp->fstamp = htonl(mvkey_info->fstamp);
2921132451Sroberto	len = i2d_DSAparams(sdsa, NULL);
2922285612Sdelphij	if (len == 0) {
2923285612Sdelphij		msyslog(LOG_ERR, "crypto_bob3: %s",
2924132451Sroberto		    ERR_error_string(ERR_get_error(), NULL));
2925132451Sroberto		DSA_free(sdsa);
2926182007Sroberto		return (XEVNT_ERR);
2927132451Sroberto	}
2928132451Sroberto	vp->vallen = htonl(len);
2929132451Sroberto	ptr = emalloc(len);
2930132451Sroberto	vp->ptr = ptr;
2931132451Sroberto	i2d_DSAparams(sdsa, &ptr);
2932132451Sroberto	DSA_free(sdsa);
2933132451Sroberto	if (tstamp == 0)
2934132451Sroberto		return (XEVNT_OK);
2935182007Sroberto
2936132451Sroberto	vp->sig = emalloc(sign_siglen);
2937132451Sroberto	EVP_SignInit(&ctx, sign_digest);
2938132451Sroberto	EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2939132451Sroberto	EVP_SignUpdate(&ctx, vp->ptr, len);
2940285612Sdelphij	if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
2941289999Sglebius		INSIST(len <= sign_siglen);
2942132451Sroberto		vp->siglen = htonl(len);
2943285612Sdelphij	}
2944132451Sroberto	return (XEVNT_OK);
2945132451Sroberto}
2946132451Sroberto
2947132451Sroberto
2948132451Sroberto/*
2949132451Sroberto * crypto_mv - verify Bob's response to Alice's challenge
2950132451Sroberto *
2951132451Sroberto * Returns
2952132451Sroberto * XEVNT_OK	success
2953182007Sroberto * XEVNT_ERR	protocol error
2954132451Sroberto * XEVNT_FSP	bad filestamp
2955285612Sdelphij * XEVNT_ID	bad or missing group key
2956285612Sdelphij * XEVNT_PUB	bad or missing public key
2957132451Sroberto */
2958132451Srobertoint
2959132451Srobertocrypto_mv(
2960132451Sroberto	struct exten *ep,	/* extension pointer */
2961132451Sroberto	struct peer *peer	/* peer structure pointer */
2962132451Sroberto	)
2963132451Sroberto{
2964132451Sroberto	DSA	*dsa;		/* MV parameters */
2965132451Sroberto	DSA	*sdsa;		/* DSA parameters */
2966132451Sroberto	BN_CTX	*bctx;		/* BIGNUM context */
2967132451Sroberto	BIGNUM	*k, *u, *v;
2968132451Sroberto	u_int	len;
2969285612Sdelphij	const u_char *ptr;
2970132451Sroberto	int	temp;
2971132451Sroberto
2972132451Sroberto	/*
2973132451Sroberto	 * If the MV parameters are not valid or no challenge was sent,
2974132451Sroberto	 * something awful happened or we are being tormented.
2975132451Sroberto	 */
2976132451Sroberto	if (peer->ident_pkey == NULL) {
2977285612Sdelphij		msyslog(LOG_NOTICE, "crypto_mv: scheme unavailable");
2978182007Sroberto		return (XEVNT_ID);
2979132451Sroberto	}
2980285612Sdelphij	if (ntohl(ep->fstamp) != peer->ident_pkey->fstamp) {
2981285612Sdelphij		msyslog(LOG_NOTICE, "crypto_mv: invalid filestamp %u",
2982132451Sroberto		    ntohl(ep->fstamp));
2983132451Sroberto		return (XEVNT_FSP);
2984132451Sroberto	}
2985285612Sdelphij	if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) {
2986285612Sdelphij		msyslog(LOG_NOTICE, "crypto_mv: defective key");
2987132451Sroberto		return (XEVNT_PUB);
2988132451Sroberto	}
2989132451Sroberto	if (peer->iffval == NULL) {
2990285612Sdelphij		msyslog(LOG_NOTICE, "crypto_mv: missing challenge");
2991182007Sroberto		return (XEVNT_ID);
2992132451Sroberto	}
2993132451Sroberto
2994132451Sroberto	/*
2995285612Sdelphij	 * Extract the y, gbar and ghat values from the response.
2996132451Sroberto	 */
2997132451Sroberto	bctx = BN_CTX_new(); k = BN_new(); u = BN_new(); v = BN_new();
2998132451Sroberto	len = ntohl(ep->vallen);
2999285612Sdelphij	ptr = (u_char *)ep->pkt;
3000132451Sroberto	if ((sdsa = d2i_DSAparams(NULL, &ptr, len)) == NULL) {
3001285612Sdelphij		msyslog(LOG_ERR, "crypto_mv: %s",
3002132451Sroberto		    ERR_error_string(ERR_get_error(), NULL));
3003182007Sroberto		return (XEVNT_ERR);
3004132451Sroberto	}
3005132451Sroberto
3006132451Sroberto	/*
3007285612Sdelphij	 * Compute (gbar^xhat ghat^xbar) mod p.
3008132451Sroberto	 */
3009132451Sroberto	BN_mod_exp(u, sdsa->q, dsa->pub_key, dsa->p, bctx);
3010132451Sroberto	BN_mod_exp(v, sdsa->g, dsa->priv_key, dsa->p, bctx);
3011132451Sroberto	BN_mod_mul(u, u, v, dsa->p, bctx);
3012285612Sdelphij	BN_mod_mul(u, u, sdsa->p, dsa->p, bctx);
3013132451Sroberto
3014132451Sroberto	/*
3015285612Sdelphij	 * The result should match r.
3016132451Sroberto	 */
3017285612Sdelphij	temp = BN_cmp(u, peer->iffval);
3018132451Sroberto	BN_CTX_free(bctx); BN_free(k); BN_free(u); BN_free(v);
3019132451Sroberto	BN_free(peer->iffval);
3020132451Sroberto	peer->iffval = NULL;
3021132451Sroberto	DSA_free(sdsa);
3022132451Sroberto	if (temp == 0)
3023132451Sroberto		return (XEVNT_OK);
3024182007Sroberto
3025285612Sdelphij	msyslog(LOG_NOTICE, "crypto_mv: identity not verified");
3026285612Sdelphij	return (XEVNT_ID);
3027132451Sroberto}
3028132451Sroberto
3029132451Sroberto
3030132451Sroberto/*
3031132451Sroberto ***********************************************************************
3032132451Sroberto *								       *
3033132451Sroberto * The following routines are used to manipulate certificates          *
3034132451Sroberto *								       *
3035132451Sroberto ***********************************************************************
3036132451Sroberto */
3037132451Sroberto/*
3038182007Sroberto * cert_sign - sign x509 certificate equest and update value structure.
3039132451Sroberto *
3040182007Sroberto * The certificate request includes a copy of the host certificate,
3041182007Sroberto * which includes the version number, subject name and public key of the
3042182007Sroberto * host. The resulting certificate includes these values plus the
3043182007Sroberto * serial number, issuer name and valid interval of the server. The
3044182007Sroberto * valid interval extends from the current time to the same time one
3045182007Sroberto * year hence. This may extend the life of the signed certificate beyond
3046182007Sroberto * that of the signer certificate.
3047132451Sroberto *
3048182007Sroberto * It is convenient to use the NTP seconds of the current time as the
3049182007Sroberto * serial number. In the value structure the timestamp is the current
3050182007Sroberto * time and the filestamp is taken from the extension field. Note this
3051182007Sroberto * routine is called only when the client clock is synchronized to a
3052182007Sroberto * proventic source, so timestamp comparisons are valid.
3053182007Sroberto *
3054182007Sroberto * The host certificate is valid from the time it was generated for a
3055182007Sroberto * period of one year. A signed certificate is valid from the time of
3056182007Sroberto * signature for a period of one year, but only the host certificate (or
3057182007Sroberto * sign certificate if used) is actually used to encrypt and decrypt
3058182007Sroberto * signatures. The signature trail is built from the client via the
3059182007Sroberto * intermediate servers to the trusted server. Each signature on the
3060182007Sroberto * trail must be valid at the time of signature, but it could happen
3061182007Sroberto * that a signer certificate expire before the signed certificate, which
3062182007Sroberto * remains valid until its expiration.
3063182007Sroberto *
3064132451Sroberto * Returns
3065132451Sroberto * XEVNT_OK	success
3066285612Sdelphij * XEVNT_CRT	bad or missing certificate
3067285612Sdelphij * XEVNT_PER	host certificate expired
3068132451Sroberto * XEVNT_PUB	bad or missing public key
3069132451Sroberto * XEVNT_VFY	certificate not verified
307082498Sroberto */
3071132451Srobertostatic int
3072132451Srobertocert_sign(
3073132451Sroberto	struct exten *ep,	/* extension field pointer */
3074132451Sroberto	struct value *vp	/* value pointer */
307582498Sroberto	)
307682498Sroberto{
3077132451Sroberto	X509	*req;		/* X509 certificate request */
3078132451Sroberto	X509	*cert;		/* X509 certificate */
3079132451Sroberto	X509_EXTENSION *ext;	/* certificate extension */
3080132451Sroberto	ASN1_INTEGER *serial;	/* serial number */
3081132451Sroberto	X509_NAME *subj;	/* distinguished (common) name */
3082132451Sroberto	EVP_PKEY *pkey;		/* public key */
3083132451Sroberto	EVP_MD_CTX ctx;		/* message digest context */
3084132451Sroberto	tstamp_t tstamp;	/* NTP timestamp */
3085285612Sdelphij	struct calendar tscal;
3086132451Sroberto	u_int	len;
3087285612Sdelphij	const u_char *cptr;
3088285612Sdelphij	u_char *ptr;
3089132451Sroberto	int	i, temp;
309082498Sroberto
309182498Sroberto	/*
3092132451Sroberto	 * Decode ASN.1 objects and construct certificate structure.
3093182007Sroberto	 * Make sure the system clock is synchronized to a proventic
3094182007Sroberto	 * source.
309582498Sroberto	 */
3096132451Sroberto	tstamp = crypto_time();
3097132451Sroberto	if (tstamp == 0)
3098132451Sroberto		return (XEVNT_TSP);
3099132451Sroberto
3100289999Sglebius	len = exten_payload_size(ep);
3101289999Sglebius	if (len == 0 || len > MAX_VALLEN)
3102289999Sglebius		return (XEVNT_LEN);
3103285612Sdelphij	cptr = (void *)ep->pkt;
3104289999Sglebius	if ((req = d2i_X509(NULL, &cptr, len)) == NULL) {
3105285612Sdelphij		msyslog(LOG_ERR, "cert_sign: %s",
3106132451Sroberto		    ERR_error_string(ERR_get_error(), NULL));
3107132451Sroberto		return (XEVNT_CRT);
310882498Sroberto	}
3109132451Sroberto	/*
3110132451Sroberto	 * Extract public key and check for errors.
3111132451Sroberto	 */
3112132451Sroberto	if ((pkey = X509_get_pubkey(req)) == NULL) {
3113285612Sdelphij		msyslog(LOG_ERR, "cert_sign: %s",
3114132451Sroberto		    ERR_error_string(ERR_get_error(), NULL));
3115132451Sroberto		X509_free(req);
3116132451Sroberto		return (XEVNT_PUB);
3117132451Sroberto	}
311882498Sroberto
311982498Sroberto	/*
3120285612Sdelphij	 * Generate X509 certificate signed by this server. If this is a
3121285612Sdelphij	 * trusted host, the issuer name is the group name; otherwise,
3122285612Sdelphij	 * it is the host name. Also copy any extensions that might be
3123285612Sdelphij	 * present.
312482498Sroberto	 */
3125132451Sroberto	cert = X509_new();
3126132451Sroberto	X509_set_version(cert, X509_get_version(req));
3127132451Sroberto	serial = ASN1_INTEGER_new();
3128132451Sroberto	ASN1_INTEGER_set(serial, tstamp);
3129132451Sroberto	X509_set_serialNumber(cert, serial);
3130132451Sroberto	X509_gmtime_adj(X509_get_notBefore(cert), 0L);
3131132451Sroberto	X509_gmtime_adj(X509_get_notAfter(cert), YEAR);
3132132451Sroberto	subj = X509_get_issuer_name(cert);
3133132451Sroberto	X509_NAME_add_entry_by_txt(subj, "commonName", MBSTRING_ASC,
3134285612Sdelphij	    hostval.ptr, strlen((const char *)hostval.ptr), -1, 0);
3135132451Sroberto	subj = X509_get_subject_name(req);
3136132451Sroberto	X509_set_subject_name(cert, subj);
3137132451Sroberto	X509_set_pubkey(cert, pkey);
3138132451Sroberto	temp = X509_get_ext_count(req);
3139132451Sroberto	for (i = 0; i < temp; i++) {
3140132451Sroberto		ext = X509_get_ext(req, i);
3141285612Sdelphij		INSIST(X509_add_ext(cert, ext, -1));
314282498Sroberto	}
3143132451Sroberto	X509_free(req);
314482498Sroberto
314582498Sroberto	/*
3146285612Sdelphij	 * Sign and verify the client certificate, but only if the host
3147285612Sdelphij	 * certificate has not expired.
314882498Sroberto	 */
3149285612Sdelphij	(void)ntpcal_ntp_to_date(&tscal, tstamp, NULL);
3150285612Sdelphij	if ((calcomp(&tscal, &(cert_host->first)) < 0)
3151285612Sdelphij	|| (calcomp(&tscal, &(cert_host->last)) > 0)) {
3152285612Sdelphij		X509_free(cert);
3153285612Sdelphij		return (XEVNT_PER);
3154285612Sdelphij	}
3155132451Sroberto	X509_sign(cert, sign_pkey, sign_digest);
3156285612Sdelphij	if (X509_verify(cert, sign_pkey) <= 0) {
3157285612Sdelphij		msyslog(LOG_ERR, "cert_sign: %s",
3158132451Sroberto		    ERR_error_string(ERR_get_error(), NULL));
3159132451Sroberto		X509_free(cert);
3160132451Sroberto		return (XEVNT_VFY);
3161132451Sroberto	}
3162132451Sroberto	len = i2d_X509(cert, NULL);
316382498Sroberto
316482498Sroberto	/*
3165132451Sroberto	 * Build and sign the value structure. We have to sign it here,
3166132451Sroberto	 * since the response has to be returned right away. This is a
3167132451Sroberto	 * clogging hazard.
316882498Sroberto	 */
3169132451Sroberto	memset(vp, 0, sizeof(struct value));
3170132451Sroberto	vp->tstamp = htonl(tstamp);
3171132451Sroberto	vp->fstamp = ep->fstamp;
3172132451Sroberto	vp->vallen = htonl(len);
3173132451Sroberto	vp->ptr = emalloc(len);
3174132451Sroberto	ptr = vp->ptr;
3175285612Sdelphij	i2d_X509(cert, (unsigned char **)(intptr_t)&ptr);
3176132451Sroberto	vp->siglen = 0;
3177285612Sdelphij	if (tstamp != 0) {
3178285612Sdelphij		vp->sig = emalloc(sign_siglen);
3179285612Sdelphij		EVP_SignInit(&ctx, sign_digest);
3180285612Sdelphij		EVP_SignUpdate(&ctx, (u_char *)vp, 12);
3181285612Sdelphij		EVP_SignUpdate(&ctx, vp->ptr, len);
3182285612Sdelphij		if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
3183289999Sglebius			INSIST(len <= sign_siglen);
3184285612Sdelphij			vp->siglen = htonl(len);
3185285612Sdelphij		}
3186285612Sdelphij	}
318782498Sroberto#ifdef DEBUG
3188132451Sroberto	if (debug > 1)
3189132451Sroberto		X509_print_fp(stdout, cert);
319082498Sroberto#endif
3191132451Sroberto	X509_free(cert);
3192132451Sroberto	return (XEVNT_OK);
319382498Sroberto}
319482498Sroberto
319582498Sroberto
319682498Sroberto/*
3197285612Sdelphij * cert_install - install certificate in certificate cache
3198132451Sroberto *
3199132451Sroberto * This routine encodes an extension field into a certificate info/value
3200132451Sroberto * structure. It searches the certificate list for duplicates and
3201285612Sdelphij * expunges whichever is older. Finally, it inserts this certificate
3202285612Sdelphij * first on the list.
3203132451Sroberto *
3204285612Sdelphij * Returns certificate info pointer if valid, NULL if not.
3205132451Sroberto */
3206285612Sdelphijstruct cert_info *
3207132451Srobertocert_install(
3208132451Sroberto	struct exten *ep,	/* cert info/value */
3209132451Sroberto	struct peer *peer	/* peer structure */
3210132451Sroberto	)
3211132451Sroberto{
3212285612Sdelphij	struct cert_info *cp, *xp, **zp;
3213132451Sroberto
321482498Sroberto	/*
3215132451Sroberto	 * Parse and validate the signed certificate. If valid,
3216285612Sdelphij	 * construct the info/value structure; otherwise, scamper home
3217285612Sdelphij	 * empty handed.
321882498Sroberto	 */
3219285612Sdelphij	if ((cp = cert_parse((u_char *)ep->pkt, (long)ntohl(ep->vallen),
3220285612Sdelphij	    (tstamp_t)ntohl(ep->fstamp))) == NULL)
3221285612Sdelphij		return (NULL);
3222132451Sroberto
3223132451Sroberto	/*
3224132451Sroberto	 * Scan certificate list looking for another certificate with
3225132451Sroberto	 * the same subject and issuer. If another is found with the
3226132451Sroberto	 * same or older filestamp, unlink it and return the goodies to
3227182007Sroberto	 * the heap. If another is found with a later filestamp, discard
3228285612Sdelphij	 * the new one and leave the building with the old one.
3229182007Sroberto	 *
3230182007Sroberto	 * Make a note to study this issue again. An earlier certificate
3231182007Sroberto	 * with a long lifetime might be overtaken by a later
3232182007Sroberto	 * certificate with a short lifetime, thus invalidating the
3233182007Sroberto	 * earlier signature. However, we gotta find a way to leak old
3234182007Sroberto	 * stuff from the cache, so we do it anyway.
3235132451Sroberto	 */
3236132451Sroberto	zp = &cinfo;
3237132451Sroberto	for (xp = cinfo; xp != NULL; xp = xp->link) {
3238132451Sroberto		if (strcmp(cp->subject, xp->subject) == 0 &&
3239132451Sroberto		    strcmp(cp->issuer, xp->issuer) == 0) {
3240132451Sroberto			if (ntohl(cp->cert.fstamp) <=
3241132451Sroberto			    ntohl(xp->cert.fstamp)) {
3242285612Sdelphij				cert_free(cp);
3243285612Sdelphij				cp = xp;
3244285612Sdelphij			} else {
3245285612Sdelphij				*zp = xp->link;
3246132451Sroberto				cert_free(xp);
3247285612Sdelphij				xp = NULL;
3248132451Sroberto			}
3249132451Sroberto			break;
3250132451Sroberto		}
3251132451Sroberto		zp = &xp->link;
3252132451Sroberto	}
3253285612Sdelphij	if (xp == NULL) {
3254285612Sdelphij		cp->link = cinfo;
3255285612Sdelphij		cinfo = cp;
3256285612Sdelphij	}
3257285612Sdelphij	cp->flags |= CERT_VALID;
3258285612Sdelphij	crypto_update();
3259285612Sdelphij	return (cp);
3260285612Sdelphij}
3261132451Sroberto
3262285612Sdelphij
3263285612Sdelphij/*
3264285612Sdelphij * cert_hike - verify the signature using the issuer public key
3265285612Sdelphij *
3266285612Sdelphij * Returns
3267285612Sdelphij * XEVNT_OK	success
3268285612Sdelphij * XEVNT_CRT	bad or missing certificate
3269285612Sdelphij * XEVNT_PER	host certificate expired
3270285612Sdelphij * XEVNT_VFY	certificate not verified
3271285612Sdelphij */
3272285612Sdelphijint
3273285612Sdelphijcert_hike(
3274285612Sdelphij	struct peer *peer,	/* peer structure pointer */
3275285612Sdelphij	struct cert_info *yp	/* issuer certificate */
3276285612Sdelphij	)
3277285612Sdelphij{
3278285612Sdelphij	struct cert_info *xp;	/* subject certificate */
3279285612Sdelphij	X509	*cert;		/* X509 certificate */
3280285612Sdelphij	const u_char *ptr;
3281285612Sdelphij
3282132451Sroberto	/*
3283285612Sdelphij	 * Save the issuer on the new certificate, but remember the old
3284285612Sdelphij	 * one.
3285132451Sroberto	 */
3286285612Sdelphij	if (peer->issuer != NULL)
3287285612Sdelphij		free(peer->issuer);
3288285612Sdelphij	peer->issuer = estrdup(yp->issuer);
3289285612Sdelphij	xp = peer->xinfo;
3290285612Sdelphij	peer->xinfo = yp;
3291132451Sroberto
3292285612Sdelphij	/*
3293285612Sdelphij	 * If subject Y matches issuer Y, then the certificate trail is
3294285612Sdelphij	 * complete. If Y is not trusted, the server certificate has yet
3295285612Sdelphij	 * been signed, so keep trying. Otherwise, save the group key
3296285612Sdelphij	 * and light the valid bit. If the host certificate is trusted,
3297285612Sdelphij	 * do not execute a sign exchange. If no identity scheme is in
3298285612Sdelphij	 * use, light the identity and proventic bits.
3299285612Sdelphij	 */
3300285612Sdelphij	if (strcmp(yp->subject, yp->issuer) == 0) {
3301285612Sdelphij		if (!(yp->flags & CERT_TRUST))
3302285612Sdelphij			return (XEVNT_OK);
3303132451Sroberto
3304285612Sdelphij		/*
3305285612Sdelphij		 * If the server has an an identity scheme, fetch the
3306285612Sdelphij		 * identity credentials. If not, the identity is
3307285612Sdelphij		 * verified only by the trusted certificate. The next
3308285612Sdelphij		 * signature will set the server proventic.
3309285612Sdelphij		 */
3310285612Sdelphij		peer->crypto |= CRYPTO_FLAG_CERT;
3311285612Sdelphij		peer->grpkey = yp->grpkey;
3312285612Sdelphij		if (peer->ident == NULL || !(peer->crypto &
3313285612Sdelphij		    CRYPTO_FLAG_MASK))
3314285612Sdelphij			peer->crypto |= CRYPTO_FLAG_VRFY;
3315285612Sdelphij	}
3316132451Sroberto
3317285612Sdelphij	/*
3318285612Sdelphij	 * If X exists, verify signature X using public key Y.
3319285612Sdelphij	 */
3320285612Sdelphij	if (xp == NULL)
3321285612Sdelphij		return (XEVNT_OK);
3322182007Sroberto
3323285612Sdelphij	ptr = (u_char *)xp->cert.ptr;
3324285612Sdelphij	cert = d2i_X509(NULL, &ptr, ntohl(xp->cert.vallen));
3325285612Sdelphij	if (cert == NULL) {
3326285612Sdelphij		xp->flags |= CERT_ERROR;
3327285612Sdelphij		return (XEVNT_CRT);
3328285612Sdelphij	}
3329285612Sdelphij	if (X509_verify(cert, yp->pkey) <= 0) {
3330285612Sdelphij		X509_free(cert);
3331285612Sdelphij		xp->flags |= CERT_ERROR;
3332285612Sdelphij		return (XEVNT_VFY);
3333285612Sdelphij	}
3334285612Sdelphij	X509_free(cert);
3335182007Sroberto
3336285612Sdelphij	/*
3337285612Sdelphij	 * Signature X is valid only if it begins during the
3338285612Sdelphij	 * lifetime of Y.
3339285612Sdelphij	 */
3340285612Sdelphij	if ((calcomp(&(xp->first), &(yp->first)) < 0)
3341285612Sdelphij	|| (calcomp(&(xp->first), &(yp->last)) > 0)) {
3342285612Sdelphij		xp->flags |= CERT_ERROR;
3343285612Sdelphij		return (XEVNT_PER);
3344285612Sdelphij	}
3345285612Sdelphij	xp->flags |= CERT_SIGN;
3346285612Sdelphij	return (XEVNT_OK);
3347285612Sdelphij}
3348132451Sroberto
3349132451Sroberto
3350285612Sdelphij/*
3351285612Sdelphij * cert_parse - parse x509 certificate and create info/value structures.
3352285612Sdelphij *
3353285612Sdelphij * The server certificate includes the version number, issuer name,
3354285612Sdelphij * subject name, public key and valid date interval. If the issuer name
3355285612Sdelphij * is the same as the subject name, the certificate is self signed and
3356285612Sdelphij * valid only if the server is configured as trustable. If the names are
3357285612Sdelphij * different, another issuer has signed the server certificate and
3358285612Sdelphij * vouched for it. In this case the server certificate is valid if
3359285612Sdelphij * verified by the issuer public key.
3360285612Sdelphij *
3361285612Sdelphij * Returns certificate info/value pointer if valid, NULL if not.
3362285612Sdelphij */
3363285612Sdelphijstruct cert_info *		/* certificate information structure */
3364285612Sdelphijcert_parse(
3365285612Sdelphij	const u_char *asn1cert,	/* X509 certificate */
3366285612Sdelphij	long	len,		/* certificate length */
3367285612Sdelphij	tstamp_t fstamp		/* filestamp */
3368285612Sdelphij	)
3369285612Sdelphij{
3370285612Sdelphij	X509	*cert;		/* X509 certificate */
3371285612Sdelphij	X509_EXTENSION *ext;	/* X509v3 extension */
3372285612Sdelphij	struct cert_info *ret;	/* certificate info/value */
3373285612Sdelphij	BIO	*bp;
3374285612Sdelphij	char	pathbuf[MAXFILENAME];
3375285612Sdelphij	const u_char *ptr;
3376285612Sdelphij	char	*pch;
3377285612Sdelphij	int	temp, cnt, i;
3378285612Sdelphij	struct calendar fscal;
3379132451Sroberto
3380285612Sdelphij	/*
3381285612Sdelphij	 * Decode ASN.1 objects and construct certificate structure.
3382285612Sdelphij	 */
3383285612Sdelphij	ptr = asn1cert;
3384285612Sdelphij	if ((cert = d2i_X509(NULL, &ptr, len)) == NULL) {
3385285612Sdelphij		msyslog(LOG_ERR, "cert_parse: %s",
3386285612Sdelphij		    ERR_error_string(ERR_get_error(), NULL));
3387285612Sdelphij		return (NULL);
3388285612Sdelphij	}
3389285612Sdelphij#ifdef DEBUG
3390285612Sdelphij	if (debug > 1)
3391285612Sdelphij		X509_print_fp(stdout, cert);
3392285612Sdelphij#endif
3393132451Sroberto
3394285612Sdelphij	/*
3395285612Sdelphij	 * Extract version, subject name and public key.
3396285612Sdelphij	 */
3397285612Sdelphij	ret = emalloc_zero(sizeof(*ret));
3398285612Sdelphij	if ((ret->pkey = X509_get_pubkey(cert)) == NULL) {
3399285612Sdelphij		msyslog(LOG_ERR, "cert_parse: %s",
3400285612Sdelphij		    ERR_error_string(ERR_get_error(), NULL));
3401285612Sdelphij		cert_free(ret);
3402285612Sdelphij		X509_free(cert);
3403285612Sdelphij		return (NULL);
3404285612Sdelphij	}
3405285612Sdelphij	ret->version = X509_get_version(cert);
3406285612Sdelphij	X509_NAME_oneline(X509_get_subject_name(cert), pathbuf,
3407285612Sdelphij	    sizeof(pathbuf));
3408285612Sdelphij	pch = strstr(pathbuf, "CN=");
3409285612Sdelphij	if (NULL == pch) {
3410285612Sdelphij		msyslog(LOG_NOTICE, "cert_parse: invalid subject %s",
3411285612Sdelphij		    pathbuf);
3412285612Sdelphij		cert_free(ret);
3413285612Sdelphij		X509_free(cert);
3414285612Sdelphij		return (NULL);
3415285612Sdelphij	}
3416285612Sdelphij	ret->subject = estrdup(pch + 3);
3417132451Sroberto
3418285612Sdelphij	/*
3419285612Sdelphij	 * Extract remaining objects. Note that the NTP serial number is
3420285612Sdelphij	 * the NTP seconds at the time of signing, but this might not be
3421285612Sdelphij	 * the case for other authority. We don't bother to check the
3422285612Sdelphij	 * objects at this time, since the real crunch can happen only
3423285612Sdelphij	 * when the time is valid but not yet certificated.
3424285612Sdelphij	 */
3425285612Sdelphij	ret->nid = OBJ_obj2nid(cert->cert_info->signature->algorithm);
3426285612Sdelphij	ret->digest = (const EVP_MD *)EVP_get_digestbynid(ret->nid);
3427285612Sdelphij	ret->serial =
3428285612Sdelphij	    (u_long)ASN1_INTEGER_get(X509_get_serialNumber(cert));
3429285612Sdelphij	X509_NAME_oneline(X509_get_issuer_name(cert), pathbuf,
3430285612Sdelphij	    sizeof(pathbuf));
3431285612Sdelphij	if ((pch = strstr(pathbuf, "CN=")) == NULL) {
3432285612Sdelphij		msyslog(LOG_NOTICE, "cert_parse: invalid issuer %s",
3433285612Sdelphij		    pathbuf);
3434285612Sdelphij		cert_free(ret);
3435285612Sdelphij		X509_free(cert);
3436285612Sdelphij		return (NULL);
3437285612Sdelphij	}
3438285612Sdelphij	ret->issuer = estrdup(pch + 3);
3439285612Sdelphij	asn_to_calendar(X509_get_notBefore(cert), &(ret->first));
3440285612Sdelphij	asn_to_calendar(X509_get_notAfter(cert), &(ret->last));
3441285612Sdelphij
3442285612Sdelphij	/*
3443285612Sdelphij	 * Extract extension fields. These are ad hoc ripoffs of
3444285612Sdelphij	 * currently assigned functions and will certainly be changed
3445285612Sdelphij	 * before prime time.
3446285612Sdelphij	 */
3447285612Sdelphij	cnt = X509_get_ext_count(cert);
3448285612Sdelphij	for (i = 0; i < cnt; i++) {
3449285612Sdelphij		ext = X509_get_ext(cert, i);
3450285612Sdelphij		temp = OBJ_obj2nid(ext->object);
3451285612Sdelphij		switch (temp) {
3452285612Sdelphij
3453285612Sdelphij		/*
3454285612Sdelphij		 * If a key_usage field is present, we decode whether
3455285612Sdelphij		 * this is a trusted or private certificate. This is
3456285612Sdelphij		 * dorky; all we want is to compare NIDs, but OpenSSL
3457285612Sdelphij		 * insists on BIO text strings.
3458285612Sdelphij		 */
3459285612Sdelphij		case NID_ext_key_usage:
3460285612Sdelphij			bp = BIO_new(BIO_s_mem());
3461285612Sdelphij			X509V3_EXT_print(bp, ext, 0, 0);
3462285612Sdelphij			BIO_gets(bp, pathbuf, sizeof(pathbuf));
3463285612Sdelphij			BIO_free(bp);
3464285612Sdelphij			if (strcmp(pathbuf, "Trust Root") == 0)
3465285612Sdelphij				ret->flags |= CERT_TRUST;
3466285612Sdelphij			else if (strcmp(pathbuf, "Private") == 0)
3467285612Sdelphij				ret->flags |= CERT_PRIV;
3468285612Sdelphij			DPRINTF(1, ("cert_parse: %s: %s\n",
3469285612Sdelphij				    OBJ_nid2ln(temp), pathbuf));
3470285612Sdelphij			break;
3471285612Sdelphij
3472285612Sdelphij		/*
3473285612Sdelphij		 * If a NID_subject_key_identifier field is present, it
3474285612Sdelphij		 * contains the GQ public key.
3475285612Sdelphij		 */
3476285612Sdelphij		case NID_subject_key_identifier:
3477285612Sdelphij			ret->grpkey = BN_bin2bn(&ext->value->data[2],
3478285612Sdelphij			    ext->value->length - 2, NULL);
3479285612Sdelphij			/* fall through */
3480285612Sdelphij		default:
3481285612Sdelphij			DPRINTF(1, ("cert_parse: %s\n",
3482285612Sdelphij				    OBJ_nid2ln(temp)));
3483285612Sdelphij			break;
3484132451Sroberto		}
3485132451Sroberto	}
3486285612Sdelphij	if (strcmp(ret->subject, ret->issuer) == 0) {
3487132451Sroberto
3488285612Sdelphij		/*
3489285612Sdelphij		 * If certificate is self signed, verify signature.
3490285612Sdelphij		 */
3491285612Sdelphij		if (X509_verify(cert, ret->pkey) <= 0) {
3492285612Sdelphij			msyslog(LOG_NOTICE,
3493285612Sdelphij			    "cert_parse: signature not verified %s",
3494285612Sdelphij			    ret->subject);
3495285612Sdelphij			cert_free(ret);
3496285612Sdelphij			X509_free(cert);
3497285612Sdelphij			return (NULL);
3498285612Sdelphij		}
3499285612Sdelphij	} else {
3500285612Sdelphij
3501285612Sdelphij		/*
3502285612Sdelphij		 * Check for a certificate loop.
3503285612Sdelphij		 */
3504285612Sdelphij		if (strcmp((const char *)hostval.ptr, ret->issuer) == 0) {
3505285612Sdelphij			msyslog(LOG_NOTICE,
3506285612Sdelphij			    "cert_parse: certificate trail loop %s",
3507285612Sdelphij			    ret->subject);
3508285612Sdelphij			cert_free(ret);
3509285612Sdelphij			X509_free(cert);
3510285612Sdelphij			return (NULL);
3511285612Sdelphij		}
3512285612Sdelphij	}
3513285612Sdelphij
3514132451Sroberto	/*
3515285612Sdelphij	 * Verify certificate valid times. Note that certificates cannot
3516285612Sdelphij	 * be retroactive.
3517132451Sroberto	 */
3518285612Sdelphij	(void)ntpcal_ntp_to_date(&fscal, fstamp, NULL);
3519285612Sdelphij	if ((calcomp(&(ret->first), &(ret->last)) > 0)
3520285612Sdelphij	|| (calcomp(&(ret->first), &fscal) < 0)) {
3521285612Sdelphij		msyslog(LOG_NOTICE,
3522285612Sdelphij		    "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",
3523285612Sdelphij		    ret->subject,
3524285612Sdelphij		    ret->first.year, ret->first.month, ret->first.monthday,
3525285612Sdelphij		    ret->first.hour, ret->first.minute, ret->first.second,
3526285612Sdelphij		    ret->last.year, ret->last.month, ret->last.monthday,
3527285612Sdelphij		    ret->last.hour, ret->last.minute, ret->last.second,
3528285612Sdelphij		    fscal.year, fscal.month, fscal.monthday,
3529285612Sdelphij		    fscal.hour, fscal.minute, fscal.second);
3530285612Sdelphij		cert_free(ret);
3531285612Sdelphij		X509_free(cert);
3532285612Sdelphij		return (NULL);
3533285612Sdelphij	}
3534285612Sdelphij
3535285612Sdelphij	/*
3536285612Sdelphij	 * Build the value structure to sign and send later.
3537285612Sdelphij	 */
3538285612Sdelphij	ret->cert.fstamp = htonl(fstamp);
3539285612Sdelphij	ret->cert.vallen = htonl(len);
3540285612Sdelphij	ret->cert.ptr = emalloc(len);
3541285612Sdelphij	memcpy(ret->cert.ptr, asn1cert, len);
3542285612Sdelphij	X509_free(cert);
3543285612Sdelphij	return (ret);
3544132451Sroberto}
3545132451Sroberto
3546132451Sroberto
3547132451Sroberto/*
3548132451Sroberto * cert_free - free certificate information structure
3549132451Sroberto */
3550132451Srobertovoid
3551132451Srobertocert_free(
3552132451Sroberto	struct cert_info *cinf	/* certificate info/value structure */
3553132451Sroberto	)
3554132451Sroberto{
3555132451Sroberto	if (cinf->pkey != NULL)
3556132451Sroberto		EVP_PKEY_free(cinf->pkey);
3557132451Sroberto	if (cinf->subject != NULL)
3558132451Sroberto		free(cinf->subject);
3559132451Sroberto	if (cinf->issuer != NULL)
3560132451Sroberto		free(cinf->issuer);
3561132451Sroberto	if (cinf->grpkey != NULL)
3562285612Sdelphij		BN_free(cinf->grpkey);
3563132451Sroberto	value_free(&cinf->cert);
3564132451Sroberto	free(cinf);
3565132451Sroberto}
3566132451Sroberto
3567132451Sroberto
3568132451Sroberto/*
3569285612Sdelphij * crypto_key - load cryptographic parameters and keys
3570132451Sroberto *
3571285612Sdelphij * This routine searches the key cache for matching name in the form
3572285612Sdelphij * ntpkey_<key>_<name>, where <key> is one of host, sign, iff, gq, mv,
3573285612Sdelphij * and <name> is the host/group name. If not found, it tries to load a
3574285612Sdelphij * PEM-encoded file of the same name and extracts the filestamp from
3575285612Sdelphij * the first line of the file name. It returns the key pointer if valid,
3576285612Sdelphij * NULL if not.
3577132451Sroberto */
3578285612Sdelphijstatic struct pkey_info *
3579132451Srobertocrypto_key(
3580132451Sroberto	char	*cp,		/* file name */
3581285612Sdelphij	char	*passwd1,	/* password */
3582285612Sdelphij	sockaddr_u *addr 	/* IP address */
3583132451Sroberto	)
3584132451Sroberto{
3585132451Sroberto	FILE	*str;		/* file handle */
3586285612Sdelphij	struct pkey_info *pkp;	/* generic key */
3587132451Sroberto	EVP_PKEY *pkey = NULL;	/* public/private key */
3588285612Sdelphij	tstamp_t fstamp;
3589132451Sroberto	char	filename[MAXFILENAME]; /* name of key file */
3590132451Sroberto	char	linkname[MAXFILENAME]; /* filestamp buffer) */
3591132451Sroberto	char	statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3592132451Sroberto	char	*ptr;
3593132451Sroberto
3594132451Sroberto	/*
3595285612Sdelphij	 * Search the key cache for matching key and name.
3596285612Sdelphij	 */
3597285612Sdelphij	for (pkp = pkinfo; pkp != NULL; pkp = pkp->link) {
3598285612Sdelphij		if (strcmp(cp, pkp->name) == 0)
3599285612Sdelphij			return (pkp);
3600285612Sdelphij	}
3601285612Sdelphij
3602285612Sdelphij	/*
3603132451Sroberto	 * Open the key file. If the first character of the file name is
3604132451Sroberto	 * not '/', prepend the keys directory string. If something goes
3605132451Sroberto	 * wrong, abandon ship.
3606132451Sroberto	 */
360782498Sroberto	if (*cp == '/')
3608285612Sdelphij		strlcpy(filename, cp, sizeof(filename));
360982498Sroberto	else
3610285612Sdelphij		snprintf(filename, sizeof(filename), "%s/%s", keysdir,
3611285612Sdelphij		    cp);
361282498Sroberto	str = fopen(filename, "r");
3613132451Sroberto	if (str == NULL)
3614132451Sroberto		return (NULL);
3615132451Sroberto
3616132451Sroberto	/*
3617132451Sroberto	 * Read the filestamp, which is contained in the first line.
3618132451Sroberto	 */
3619285612Sdelphij	if ((ptr = fgets(linkname, sizeof(linkname), str)) == NULL) {
3620285612Sdelphij		msyslog(LOG_ERR, "crypto_key: empty file %s",
3621132451Sroberto		    filename);
3622285612Sdelphij		fclose(str);
3623132451Sroberto		return (NULL);
362482498Sroberto	}
3625132451Sroberto	if ((ptr = strrchr(ptr, '.')) == NULL) {
3626285612Sdelphij		msyslog(LOG_ERR, "crypto_key: no filestamp %s",
3627132451Sroberto		    filename);
3628285612Sdelphij		fclose(str);
3629132451Sroberto		return (NULL);
3630132451Sroberto	}
3631285612Sdelphij	if (sscanf(++ptr, "%u", &fstamp) != 1) {
3632285612Sdelphij		msyslog(LOG_ERR, "crypto_key: invalid filestamp %s",
3633132451Sroberto		    filename);
3634285612Sdelphij		fclose(str);
3635132451Sroberto		return (NULL);
3636132451Sroberto	}
363782498Sroberto
363882498Sroberto	/*
3639285612Sdelphij	 * Read and decrypt PEM-encoded private key. If it fails to
3640285612Sdelphij	 * decrypt, game over.
364182498Sroberto	 */
3642285612Sdelphij	pkey = PEM_read_PrivateKey(str, NULL, NULL, passwd1);
3643132451Sroberto	fclose(str);
3644132451Sroberto	if (pkey == NULL) {
3645285612Sdelphij		msyslog(LOG_ERR, "crypto_key: %s",
3646132451Sroberto		    ERR_error_string(ERR_get_error(), NULL));
3647285612Sdelphij		exit (-1);
364882498Sroberto	}
364982498Sroberto
365082498Sroberto	/*
3651285612Sdelphij	 * Make a new entry in the key cache.
3652285612Sdelphij	 */
3653285612Sdelphij	pkp = emalloc(sizeof(struct pkey_info));
3654285612Sdelphij	pkp->link = pkinfo;
3655285612Sdelphij	pkinfo = pkp;
3656285612Sdelphij	pkp->pkey = pkey;
3657285612Sdelphij	pkp->name = estrdup(cp);
3658285612Sdelphij	pkp->fstamp = fstamp;
3659285612Sdelphij
3660285612Sdelphij	/*
3661132451Sroberto	 * Leave tracks in the cryptostats.
366282498Sroberto	 */
3663132451Sroberto	if ((ptr = strrchr(linkname, '\n')) != NULL)
3664132451Sroberto		*ptr = '\0';
3665285612Sdelphij	snprintf(statstr, sizeof(statstr), "%s mod %d", &linkname[2],
3666132451Sroberto	    EVP_PKEY_size(pkey) * 8);
3667285612Sdelphij	record_crypto_stats(addr, statstr);
3668285612Sdelphij
3669285612Sdelphij	DPRINTF(1, ("crypto_key: %s\n", statstr));
3670132451Sroberto#ifdef DEBUG
3671132451Sroberto	if (debug > 1) {
3672200576Sroberto		if (pkey->type == EVP_PKEY_DSA)
3673132451Sroberto			DSA_print_fp(stdout, pkey->pkey.dsa, 0);
3674285612Sdelphij		else if (pkey->type == EVP_PKEY_RSA)
3675132451Sroberto			RSA_print_fp(stdout, pkey->pkey.rsa, 0);
367682498Sroberto	}
3677132451Sroberto#endif
3678285612Sdelphij	return (pkp);
3679132451Sroberto}
368082498Sroberto
3681132451Sroberto
3682132451Sroberto/*
3683285612Sdelphij ***********************************************************************
3684285612Sdelphij *								       *
3685285612Sdelphij * The following routines are used only at initialization time         *
3686285612Sdelphij *								       *
3687285612Sdelphij ***********************************************************************
3688285612Sdelphij */
3689285612Sdelphij/*
3690132451Sroberto * crypto_cert - load certificate from file
3691132451Sroberto *
3692285612Sdelphij * This routine loads an X.509 RSA or DSA certificate from a file and
3693132451Sroberto * constructs a info/cert value structure for this machine. The
3694132451Sroberto * structure includes a filestamp extracted from the file name. Later
3695285612Sdelphij * the certificate can be sent to another machine on request.
3696132451Sroberto *
3697132451Sroberto * Returns certificate info/value pointer if valid, NULL if not.
3698132451Sroberto */
3699132451Srobertostatic struct cert_info *	/* certificate information */
3700132451Srobertocrypto_cert(
3701132451Sroberto	char	*cp		/* file name */
3702132451Sroberto	)
3703132451Sroberto{
3704132451Sroberto	struct cert_info *ret; /* certificate information */
3705132451Sroberto	FILE	*str;		/* file handle */
3706132451Sroberto	char	filename[MAXFILENAME]; /* name of certificate file */
3707132451Sroberto	char	linkname[MAXFILENAME]; /* filestamp buffer */
3708132451Sroberto	char	statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3709132451Sroberto	tstamp_t fstamp;	/* filestamp */
3710132451Sroberto	long	len;
3711132451Sroberto	char	*ptr;
3712132451Sroberto	char	*name, *header;
3713132451Sroberto	u_char	*data;
3714132451Sroberto
371582498Sroberto	/*
3716132451Sroberto	 * Open the certificate file. If the first character of the file
3717132451Sroberto	 * name is not '/', prepend the keys directory string. If
3718132451Sroberto	 * something goes wrong, abandon ship.
371982498Sroberto	 */
3720132451Sroberto	if (*cp == '/')
3721285612Sdelphij		strlcpy(filename, cp, sizeof(filename));
3722132451Sroberto	else
3723285612Sdelphij		snprintf(filename, sizeof(filename), "%s/%s", keysdir,
3724285612Sdelphij		    cp);
3725132451Sroberto	str = fopen(filename, "r");
3726132451Sroberto	if (str == NULL)
3727132451Sroberto		return (NULL);
372882498Sroberto
3729132451Sroberto	/*
3730132451Sroberto	 * Read the filestamp, which is contained in the first line.
3731132451Sroberto	 */
3732285612Sdelphij	if ((ptr = fgets(linkname, sizeof(linkname), str)) == NULL) {
3733285612Sdelphij		msyslog(LOG_ERR, "crypto_cert: empty file %s",
3734132451Sroberto		    filename);
3735285612Sdelphij		fclose(str);
3736132451Sroberto		return (NULL);
3737132451Sroberto	}
3738132451Sroberto	if ((ptr = strrchr(ptr, '.')) == NULL) {
3739285612Sdelphij		msyslog(LOG_ERR, "crypto_cert: no filestamp %s",
3740132451Sroberto		    filename);
3741285612Sdelphij		fclose(str);
3742132451Sroberto		return (NULL);
3743132451Sroberto	}
3744132451Sroberto	if (sscanf(++ptr, "%u", &fstamp) != 1) {
3745285612Sdelphij		msyslog(LOG_ERR, "crypto_cert: invalid filestamp %s",
3746132451Sroberto		    filename);
3747285612Sdelphij		fclose(str);
3748132451Sroberto		return (NULL);
3749132451Sroberto	}
375082498Sroberto
375182498Sroberto	/*
3752132451Sroberto	 * Read PEM-encoded certificate and install.
375382498Sroberto	 */
3754132451Sroberto	if (!PEM_read(str, &name, &header, &data, &len)) {
3755285612Sdelphij		msyslog(LOG_ERR, "crypto_cert: %s",
3756132451Sroberto		    ERR_error_string(ERR_get_error(), NULL));
3757285612Sdelphij		fclose(str);
3758132451Sroberto		return (NULL);
3759132451Sroberto	}
3760285612Sdelphij	fclose(str);
3761132451Sroberto	free(header);
3762285612Sdelphij	if (strcmp(name, "CERTIFICATE") != 0) {
3763285612Sdelphij		msyslog(LOG_NOTICE, "crypto_cert: wrong PEM type %s",
3764132451Sroberto		    name);
3765132451Sroberto		free(name);
3766132451Sroberto		free(data);
3767132451Sroberto		return (NULL);
3768132451Sroberto	}
3769132451Sroberto	free(name);
377082498Sroberto
377182498Sroberto	/*
3772285612Sdelphij	 * Parse certificate and generate info/value structure. The
3773285612Sdelphij	 * pointer and copy nonsense is due something broken in Solaris.
377482498Sroberto	 */
3775132451Sroberto	ret = cert_parse(data, len, fstamp);
3776132451Sroberto	free(data);
3777132451Sroberto	if (ret == NULL)
3778132451Sroberto		return (NULL);
3779182007Sroberto
3780132451Sroberto	if ((ptr = strrchr(linkname, '\n')) != NULL)
3781132451Sroberto		*ptr = '\0';
3782285612Sdelphij	snprintf(statstr, sizeof(statstr), "%s 0x%x len %lu",
3783285612Sdelphij	    &linkname[2], ret->flags, len);
3784132451Sroberto	record_crypto_stats(NULL, statstr);
3785285612Sdelphij	DPRINTF(1, ("crypto_cert: %s\n", statstr));
3786132451Sroberto	return (ret);
378782498Sroberto}
378882498Sroberto
378982498Sroberto
379082498Sroberto/*
3791285612Sdelphij * crypto_setup - load keys, certificate and identity parameters
3792132451Sroberto *
3793285612Sdelphij * This routine loads the public/private host key and certificate. If
3794285612Sdelphij * available, it loads the public/private sign key, which defaults to
3795285612Sdelphij * the host key. The host key must be RSA, but the sign key can be
3796285612Sdelphij * either RSA or DSA. If a trusted certificate, it loads the identity
3797285612Sdelphij * parameters. In either case, the public key on the certificate must
3798285612Sdelphij * agree with the sign key.
3799285612Sdelphij *
3800285612Sdelphij * Required but missing files and inconsistent data and errors are
3801285612Sdelphij * fatal. Allowing configuration to continue would be hazardous and
3802285612Sdelphij * require really messy error checks.
380382498Sroberto */
3804285612Sdelphijvoid
3805285612Sdelphijcrypto_setup(void)
380682498Sroberto{
3807285612Sdelphij	struct pkey_info *pinfo; /* private/public key */
3808285612Sdelphij	char	filename[MAXFILENAME]; /* file name buffer */
3809285612Sdelphij	char	hostname[MAXFILENAME]; /* host name buffer */
3810285612Sdelphij	char	*randfile;
3811132451Sroberto	char	statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3812285612Sdelphij	l_fp	seed;		/* crypto PRNG seed as NTP timestamp */
3813132451Sroberto	u_int	len;
3814285612Sdelphij	int	bytes;
3815285612Sdelphij	u_char	*ptr;
381682498Sroberto
381782498Sroberto	/*
3818285612Sdelphij	 * Check for correct OpenSSL version and avoid initialization in
3819285612Sdelphij	 * the case of multiple crypto commands.
382082498Sroberto	 */
3821285612Sdelphij	if (crypto_flags & CRYPTO_FLAG_ENAB) {
3822285612Sdelphij		msyslog(LOG_NOTICE,
3823285612Sdelphij		    "crypto_setup: spurious crypto command");
382482498Sroberto		return;
382582498Sroberto	}
3826285612Sdelphij	ssl_check_version();
382782498Sroberto
382882498Sroberto	/*
3829285612Sdelphij	 * Load required random seed file and seed the random number
3830285612Sdelphij	 * generator. Be default, it is found as .rnd in the user home
3831285612Sdelphij	 * directory. The root home directory may be / or /root,
3832285612Sdelphij	 * depending on the system. Wiggle the contents a bit and write
3833285612Sdelphij	 * it back so the sequence does not repeat when we next restart.
383482498Sroberto	 */
3835285612Sdelphij	if (!RAND_status()) {
3836285612Sdelphij		if (rand_file == NULL) {
3837285612Sdelphij			RAND_file_name(filename, sizeof(filename));
3838285612Sdelphij			randfile = filename;
3839285612Sdelphij		} else if (*rand_file != '/') {
3840285612Sdelphij			snprintf(filename, sizeof(filename), "%s/%s",
3841285612Sdelphij			    keysdir, rand_file);
3842285612Sdelphij			randfile = filename;
3843285612Sdelphij		} else
3844285612Sdelphij			randfile = rand_file;
3845182007Sroberto
3846285612Sdelphij		if ((bytes = RAND_load_file(randfile, -1)) == 0) {
3847285612Sdelphij			msyslog(LOG_ERR,
3848285612Sdelphij			    "crypto_setup: random seed file %s missing",
3849285612Sdelphij			    randfile);
3850285612Sdelphij			exit (-1);
3851285612Sdelphij		}
3852285612Sdelphij		arc4random_buf(&seed, sizeof(l_fp));
3853285612Sdelphij		RAND_seed(&seed, sizeof(l_fp));
3854285612Sdelphij		RAND_write_file(randfile);
3855285612Sdelphij		DPRINTF(1, ("crypto_setup: OpenSSL version %lx random seed file %s bytes read %d\n",
3856285612Sdelphij			    SSLeay(), randfile, bytes));
385782498Sroberto	}
385882498Sroberto
385982498Sroberto	/*
3860132451Sroberto	 * Initialize structures.
386182498Sroberto	 */
3862285612Sdelphij	gethostname(hostname, sizeof(hostname));
3863285612Sdelphij	if (host_filename != NULL)
3864285612Sdelphij		strlcpy(hostname, host_filename, sizeof(hostname));
3865132451Sroberto	if (passwd == NULL)
3866285612Sdelphij		passwd = estrdup(hostname);
3867132451Sroberto	memset(&hostval, 0, sizeof(hostval));
3868132451Sroberto	memset(&pubkey, 0, sizeof(pubkey));
3869132451Sroberto	memset(&tai_leap, 0, sizeof(tai_leap));
3870132451Sroberto
3871132451Sroberto	/*
3872285612Sdelphij	 * Load required host key from file "ntpkey_host_<hostname>". If
3873285612Sdelphij	 * no host key file is not found or has invalid password, life
3874285612Sdelphij	 * as we know it ends. The host key also becomes the default
3875285612Sdelphij	 * sign key.
3876132451Sroberto	 */
3877285612Sdelphij	snprintf(filename, sizeof(filename), "ntpkey_host_%s", hostname);
3878285612Sdelphij	pinfo = crypto_key(filename, passwd, NULL);
3879285612Sdelphij	if (pinfo == NULL) {
3880132451Sroberto		msyslog(LOG_ERR,
3881132451Sroberto		    "crypto_setup: host key file %s not found or corrupt",
3882285612Sdelphij		    filename);
3883132451Sroberto		exit (-1);
3884132451Sroberto	}
3885285612Sdelphij	if (pinfo->pkey->type != EVP_PKEY_RSA) {
3886132451Sroberto		msyslog(LOG_ERR,
3887132451Sroberto		    "crypto_setup: host key is not RSA key type");
3888132451Sroberto		exit (-1);
3889132451Sroberto	}
3890285612Sdelphij	host_pkey = pinfo->pkey;
3891285612Sdelphij	sign_pkey = host_pkey;
3892285612Sdelphij	hostval.fstamp = htonl(pinfo->fstamp);
3893132451Sroberto
3894132451Sroberto	/*
3895132451Sroberto	 * Construct public key extension field for agreement scheme.
3896132451Sroberto	 */
3897132451Sroberto	len = i2d_PublicKey(host_pkey, NULL);
3898132451Sroberto	ptr = emalloc(len);
3899132451Sroberto	pubkey.ptr = ptr;
3900132451Sroberto	i2d_PublicKey(host_pkey, &ptr);
3901285612Sdelphij	pubkey.fstamp = hostval.fstamp;
3902132451Sroberto	pubkey.vallen = htonl(len);
3903132451Sroberto
3904132451Sroberto	/*
3905132451Sroberto	 * Load optional sign key from file "ntpkey_sign_<hostname>". If
3906285612Sdelphij	 * available, it becomes the sign key.
3907132451Sroberto	 */
3908285612Sdelphij	snprintf(filename, sizeof(filename), "ntpkey_sign_%s", hostname);
3909285612Sdelphij	pinfo = crypto_key(filename, passwd, NULL);
3910285612Sdelphij	if (pinfo != NULL)
3911285612Sdelphij		sign_pkey = pinfo->pkey;
3912132451Sroberto
3913132451Sroberto	/*
3914285612Sdelphij	 * Load required certificate from file "ntpkey_cert_<hostname>".
3915132451Sroberto	 */
3916285612Sdelphij	snprintf(filename, sizeof(filename), "ntpkey_cert_%s", hostname);
3917285612Sdelphij	cinfo = crypto_cert(filename);
3918285612Sdelphij	if (cinfo == NULL) {
3919285612Sdelphij		msyslog(LOG_ERR,
3920285612Sdelphij		    "crypto_setup: certificate file %s not found or corrupt",
3921285612Sdelphij		    filename);
3922285612Sdelphij		exit (-1);
3923132451Sroberto	}
3924285612Sdelphij	cert_host = cinfo;
3925285612Sdelphij	sign_digest = cinfo->digest;
3926285612Sdelphij	sign_siglen = EVP_PKEY_size(sign_pkey);
3927285612Sdelphij	if (cinfo->flags & CERT_PRIV)
3928285612Sdelphij		crypto_flags |= CRYPTO_FLAG_PRIV;
3929132451Sroberto
3930132451Sroberto	/*
3931285612Sdelphij	 * The certificate must be self-signed.
3932132451Sroberto	 */
3933285612Sdelphij	if (strcmp(cinfo->subject, cinfo->issuer) != 0) {
3934285612Sdelphij		msyslog(LOG_ERR,
3935285612Sdelphij		    "crypto_setup: certificate %s is not self-signed",
3936285612Sdelphij		    filename);
3937285612Sdelphij		exit (-1);
3938132451Sroberto	}
3939285612Sdelphij	hostval.ptr = estrdup(cinfo->subject);
3940285612Sdelphij	hostval.vallen = htonl(strlen(cinfo->subject));
3941285612Sdelphij	sys_hostname = hostval.ptr;
3942285612Sdelphij	ptr = (u_char *)strchr(sys_hostname, '@');
3943285612Sdelphij	if (ptr != NULL)
3944285612Sdelphij		sys_groupname = estrdup((char *)++ptr);
3945285612Sdelphij	if (ident_filename != NULL)
3946285612Sdelphij		strlcpy(hostname, ident_filename, sizeof(hostname));
3947132451Sroberto
3948132451Sroberto	/*
3949285612Sdelphij	 * Load optional IFF parameters from file
3950285612Sdelphij	 * "ntpkey_iffkey_<hostname>".
3951132451Sroberto	 */
3952285612Sdelphij	snprintf(filename, sizeof(filename), "ntpkey_iffkey_%s",
3953285612Sdelphij	    hostname);
3954285612Sdelphij	iffkey_info = crypto_key(filename, passwd, NULL);
3955285612Sdelphij	if (iffkey_info != NULL)
3956285612Sdelphij		crypto_flags |= CRYPTO_FLAG_IFF;
3957132451Sroberto
3958132451Sroberto	/*
3959285612Sdelphij	 * Load optional GQ parameters from file
3960285612Sdelphij	 * "ntpkey_gqkey_<hostname>".
3961132451Sroberto	 */
3962285612Sdelphij	snprintf(filename, sizeof(filename), "ntpkey_gqkey_%s",
3963285612Sdelphij	    hostname);
3964285612Sdelphij	gqkey_info = crypto_key(filename, passwd, NULL);
3965285612Sdelphij	if (gqkey_info != NULL)
3966285612Sdelphij		crypto_flags |= CRYPTO_FLAG_GQ;
3967132451Sroberto
3968132451Sroberto	/*
3969285612Sdelphij	 * Load optional MV parameters from file
3970285612Sdelphij	 * "ntpkey_mvkey_<hostname>".
3971132451Sroberto	 */
3972285612Sdelphij	snprintf(filename, sizeof(filename), "ntpkey_mvkey_%s",
3973285612Sdelphij	    hostname);
3974285612Sdelphij	mvkey_info = crypto_key(filename, passwd, NULL);
3975285612Sdelphij	if (mvkey_info != NULL)
3976285612Sdelphij		crypto_flags |= CRYPTO_FLAG_MV;
3977132451Sroberto
3978132451Sroberto	/*
3979285612Sdelphij	 * We met the enemy and he is us. Now strike up the dance.
3980132451Sroberto	 */
3981285612Sdelphij	crypto_flags |= CRYPTO_FLAG_ENAB | (cinfo->nid << 16);
3982285612Sdelphij	snprintf(statstr, sizeof(statstr), "setup 0x%x host %s %s",
3983285612Sdelphij	    crypto_flags, hostname, OBJ_nid2ln(cinfo->nid));
3984285612Sdelphij	record_crypto_stats(NULL, statstr);
3985285612Sdelphij	DPRINTF(1, ("crypto_setup: %s\n", statstr));
398682498Sroberto}
398782498Sroberto
398882498Sroberto
398982498Sroberto/*
3990285612Sdelphij * crypto_config - configure data from the crypto command.
399182498Sroberto */
399282498Srobertovoid
399382498Srobertocrypto_config(
3994132451Sroberto	int	item,		/* configuration item */
3995285612Sdelphij	char	*cp		/* item name */
399682498Sroberto	)
399782498Sroberto{
3998285612Sdelphij	int	nid;
399982498Sroberto
4000285612Sdelphij	DPRINTF(1, ("crypto_config: item %d %s\n", item, cp));
400182498Sroberto
4002285612Sdelphij	switch (item) {
4003132451Sroberto
4004132451Sroberto	/*
4005285612Sdelphij	 * Set host name (host).
4006132451Sroberto	 */
400782498Sroberto	case CRYPTO_CONF_PRIV:
4008285612Sdelphij		if (NULL != host_filename)
4009285612Sdelphij			free(host_filename);
4010285612Sdelphij		host_filename = estrdup(cp);
401182498Sroberto		break;
401282498Sroberto
401382498Sroberto	/*
4014285612Sdelphij	 * Set group name (ident).
401582498Sroberto	 */
4016285612Sdelphij	case CRYPTO_CONF_IDENT:
4017285612Sdelphij		if (NULL != ident_filename)
4018285612Sdelphij			free(ident_filename);
4019285612Sdelphij		ident_filename = estrdup(cp);
402082498Sroberto		break;
402182498Sroberto
402282498Sroberto	/*
4023285612Sdelphij	 * Set private key password (pw).
402482498Sroberto	 */
4025285612Sdelphij	case CRYPTO_CONF_PW:
4026285612Sdelphij		if (NULL != passwd)
4027285612Sdelphij			free(passwd);
4028285612Sdelphij		passwd = estrdup(cp);
402982498Sroberto		break;
403082498Sroberto
403182498Sroberto	/*
4032285612Sdelphij	 * Set random seed file name (randfile).
403382498Sroberto	 */
4034285612Sdelphij	case CRYPTO_CONF_RAND:
4035285612Sdelphij		if (NULL != rand_file)
4036285612Sdelphij			free(rand_file);
4037285612Sdelphij		rand_file = estrdup(cp);
403882498Sroberto		break;
403982498Sroberto
404082498Sroberto	/*
4041285612Sdelphij	 * Set message digest NID.
404282498Sroberto	 */
4043285612Sdelphij	case CRYPTO_CONF_NID:
4044285612Sdelphij		nid = OBJ_sn2nid(cp);
4045285612Sdelphij		if (nid == 0)
4046285612Sdelphij			msyslog(LOG_ERR,
4047285612Sdelphij			    "crypto_config: invalid digest name %s", cp);
4048285612Sdelphij		else
4049285612Sdelphij			crypto_nid = nid;
405082498Sroberto		break;
405182498Sroberto	}
405282498Sroberto}
4053289999Sglebius
4054289999Sglebius/*
4055289999Sglebius * Get the  payload size (internal value length) of an extension packet.
4056289999Sglebius * If the inner value size does not match the outer packet size (that
4057289999Sglebius * is, the value would end behind the frame given by the opcode/size
4058289999Sglebius * field) the function will effectively return UINT_MAX. If the frame is
4059289999Sglebius * too short to hold a variable-sized value, the return value is zero.
4060289999Sglebius */
4061289999Sglebiusstatic u_int
4062289999Sglebiusexten_payload_size(
4063289999Sglebius	const struct exten * ep)
4064289999Sglebius{
4065289999Sglebius	typedef const u_char *BPTR;
4066289999Sglebius
4067289999Sglebius	size_t extn_size;
4068289999Sglebius	size_t data_size;
4069289999Sglebius	size_t head_size;
4070289999Sglebius
4071289999Sglebius	data_size = 0;
4072289999Sglebius	if (NULL != ep) {
4073289999Sglebius		head_size = (BPTR)(&ep->vallen + 1) - (BPTR)ep;
4074289999Sglebius		extn_size = (uint16_t)(ntohl(ep->opcode) & 0x0000ffff);
4075289999Sglebius		if (extn_size >= head_size) {
4076289999Sglebius			data_size = (uint32_t)ntohl(ep->vallen);
4077289999Sglebius			if (data_size > extn_size - head_size)
4078289999Sglebius				data_size = ~(size_t)0u;
4079289999Sglebius		}
4080289999Sglebius	}
4081289999Sglebius	return (u_int)data_size;
4082289999Sglebius}
4083285612Sdelphij# else	/* !AUTOKEY follows */
408482498Srobertoint ntp_crypto_bs_pubkey;
4085285612Sdelphij# endif	/* !AUTOKEY */
4086