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