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