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