xref: /netbsd-src/external/bsd/ntp/dist/util/ntp-keygen.c (revision 2e2322c9c07009df921d11b1268f8506affbb8ba)
1 /*	$NetBSD: ntp-keygen.c,v 1.11 2016/11/22 03:09:31 christos Exp $	*/
2 
3 /*
4  * Program to generate cryptographic keys for ntp clients and servers
5  *
6  * This program generates password encrypted data files for use with the
7  * Autokey security protocol and Network Time Protocol Version 4. Files
8  * are prefixed with a header giving the name and date of creation
9  * followed by a type-specific descriptive label and PEM-encoded data
10  * structure compatible with programs of the OpenSSL library.
11  *
12  * All file names are like "ntpkey_<type>_<hostname>.<filestamp>", where
13  * <type> is the file type, <hostname> the generating host name and
14  * <filestamp> the generation time in NTP seconds. The NTP programs
15  * expect generic names such as "ntpkey_<type>_whimsy.udel.edu" with the
16  * association maintained by soft links. Following is a list of file
17  * types; the first line is the file name and the second link name.
18  *
19  * ntpkey_MD5key_<hostname>.<filestamp>
20  * 	MD5 (128-bit) keys used to compute message digests in symmetric
21  *	key cryptography
22  *
23  * ntpkey_RSAhost_<hostname>.<filestamp>
24  * ntpkey_host_<hostname>
25  *	RSA private/public host key pair used for public key signatures
26  *
27  * ntpkey_RSAsign_<hostname>.<filestamp>
28  * ntpkey_sign_<hostname>
29  *	RSA private/public sign key pair used for public key signatures
30  *
31  * ntpkey_DSAsign_<hostname>.<filestamp>
32  * ntpkey_sign_<hostname>
33  *	DSA Private/public sign key pair used for public key signatures
34  *
35  * Available digest/signature schemes
36  *
37  * RSA:	RSA-MD2, RSA-MD5, RSA-SHA, RSA-SHA1, RSA-MDC2, EVP-RIPEMD160
38  * DSA:	DSA-SHA, DSA-SHA1
39  *
40  * ntpkey_XXXcert_<hostname>.<filestamp>
41  * ntpkey_cert_<hostname>
42  *	X509v3 certificate using RSA or DSA public keys and signatures.
43  *	XXX is a code identifying the message digest and signature
44  *	encryption algorithm
45  *
46  * Identity schemes. The key type par is used for the challenge; the key
47  * type key is used for the response.
48  *
49  * ntpkey_IFFkey_<groupname>.<filestamp>
50  * ntpkey_iffkey_<groupname>
51  *	Schnorr (IFF) identity parameters and keys
52  *
53  * ntpkey_GQkey_<groupname>.<filestamp>,
54  * ntpkey_gqkey_<groupname>
55  *	Guillou-Quisquater (GQ) identity parameters and keys
56  *
57  * ntpkey_MVkeyX_<groupname>.<filestamp>,
58  * ntpkey_mvkey_<groupname>
59  *	Mu-Varadharajan (MV) identity parameters and keys
60  *
61  * Note: Once in a while because of some statistical fluke this program
62  * fails to generate and verify some cryptographic data, as indicated by
63  * exit status -1. In this case simply run the program again. If the
64  * program does complete with exit code 0, the data are correct as
65  * verified.
66  *
67  * These cryptographic routines are characterized by the prime modulus
68  * size in bits. The default value of 512 bits is a compromise between
69  * cryptographic strength and computing time and is ordinarily
70  * considered adequate for this application. The routines have been
71  * tested with sizes of 256, 512, 1024 and 2048 bits. Not all message
72  * digest and signature encryption schemes work with sizes less than 512
73  * bits. The computing time for sizes greater than 2048 bits is
74  * prohibitive on all but the fastest processors. An UltraSPARC Blade
75  * 1000 took something over nine minutes to generate and verify the
76  * values with size 2048. An old SPARC IPC would take a week.
77  *
78  * The OpenSSL library used by this program expects a random seed file.
79  * As described in the OpenSSL documentation, the file name defaults to
80  * first the RANDFILE environment variable in the user's home directory
81  * and then .rnd in the user's home directory.
82  */
83 #ifdef HAVE_CONFIG_H
84 # include <config.h>
85 #endif
86 #include <string.h>
87 #include <stdio.h>
88 #include <stdlib.h>
89 #include <unistd.h>
90 #include <sys/stat.h>
91 #include <sys/time.h>
92 #include <sys/types.h>
93 
94 #include "ntp.h"
95 #include "ntp_random.h"
96 #include "ntp_stdlib.h"
97 #include "ntp_assert.h"
98 #include "ntp_libopts.h"
99 #include "ntp_unixtime.h"
100 #include "ntp-keygen-opts.h"
101 
102 #ifdef OPENSSL
103 #include "openssl/bn.h"
104 #include "openssl/evp.h"
105 #include "openssl/err.h"
106 #include "openssl/rand.h"
107 #include "openssl/pem.h"
108 #include "openssl/x509v3.h"
109 #include <openssl/objects.h>
110 #include "libssl_compat.h"
111 #endif	/* OPENSSL */
112 #include <ssl_applink.c>
113 
114 #define _UC(str)	((char *)(intptr_t)(str))
115 /*
116  * Cryptodefines
117  */
118 #define	MD5KEYS		10	/* number of keys generated of each type */
119 #define	MD5SIZE		20	/* maximum key size */
120 #ifdef AUTOKEY
121 #define	PLEN		512	/* default prime modulus size (bits) */
122 #define	ILEN		256	/* default identity modulus size (bits) */
123 #define	MVMAX		100	/* max MV parameters */
124 
125 /*
126  * Strings used in X509v3 extension fields
127  */
128 #define KEY_USAGE		"digitalSignature,keyCertSign"
129 #define BASIC_CONSTRAINTS	"critical,CA:TRUE"
130 #define EXT_KEY_PRIVATE		"private"
131 #define EXT_KEY_TRUST		"trustRoot"
132 #endif	/* AUTOKEY */
133 
134 /*
135  * Prototypes
136  */
137 FILE	*fheader	(const char *, const char *, const char *);
138 int	gen_md5		(const char *);
139 void	followlink	(char *, size_t);
140 #ifdef AUTOKEY
141 EVP_PKEY *gen_rsa	(const char *);
142 EVP_PKEY *gen_dsa	(const char *);
143 EVP_PKEY *gen_iffkey	(const char *);
144 EVP_PKEY *gen_gqkey	(const char *);
145 EVP_PKEY *gen_mvkey	(const char *, EVP_PKEY **);
146 void	gen_mvserv	(char *, EVP_PKEY **);
147 int	x509		(EVP_PKEY *, const EVP_MD *, char *, const char *,
148 			    char *);
149 void	cb		(int, int, void *);
150 EVP_PKEY *genkey	(const char *, const char *);
151 EVP_PKEY *readkey	(char *, char *, u_int *, EVP_PKEY **);
152 void	writekey	(char *, char *, u_int *, EVP_PKEY **);
153 u_long	asn2ntp		(ASN1_TIME *);
154 
155 static DSA* genDsaParams(int, char*);
156 static RSA* genRsaKeyPair(int, char*);
157 
158 #endif	/* AUTOKEY */
159 
160 /*
161  * Program variables
162  */
163 extern char *optarg;		/* command line argument */
164 char	const *progname;
165 u_int	lifetime = DAYSPERYEAR;	/* certificate lifetime (days) */
166 int	nkeys;			/* MV keys */
167 time_t	epoch;			/* Unix epoch (seconds) since 1970 */
168 u_int	fstamp;			/* NTP filestamp */
169 char	hostbuf[MAXHOSTNAME + 1];
170 char	*hostname = NULL;	/* host, used in cert filenames */
171 char	*groupname = NULL;	/* group name */
172 char	certnamebuf[2 * sizeof(hostbuf)];
173 char	*certname = NULL;	/* certificate subject/issuer name */
174 char	*passwd1 = NULL;	/* input private key password */
175 char	*passwd2 = NULL;	/* output private key password */
176 char	filename[MAXFILENAME + 1]; /* file name */
177 #ifdef AUTOKEY
178 u_int	modulus = PLEN;		/* prime modulus size (bits) */
179 u_int	modulus2 = ILEN;	/* identity modulus size (bits) */
180 long	d0, d1, d2, d3;		/* callback counters */
181 const EVP_CIPHER * cipher = NULL;
182 #endif	/* AUTOKEY */
183 
184 #ifdef SYS_WINNT
185 BOOL init_randfile();
186 
187 /*
188  * Don't try to follow symbolic links on Windows.  Assume link == file.
189  */
190 int
191 readlink(
192 	char *	link,
193 	char *	file,
194 	int	len
195 	)
196 {
197 	return (int)strlen(file); /* assume no overflow possible */
198 }
199 
200 /*
201  * Don't try to create symbolic links on Windows, that is supported on
202  * Vista and later only.  Instead, if CreateHardLink is available (XP
203  * and later), hardlink the linkname to the original filename.  On
204  * earlier systems, user must rename file to match expected link for
205  * ntpd to find it.  To allow building a ntp-keygen.exe which loads on
206  * Windows pre-XP, runtime link to CreateHardLinkA().
207  */
208 int
209 symlink(
210 	char *	filename,
211 	char*	linkname
212 	)
213 {
214 	typedef BOOL (WINAPI *PCREATEHARDLINKA)(
215 		__in LPCSTR	lpFileName,
216 		__in LPCSTR	lpExistingFileName,
217 		__reserved LPSECURITY_ATTRIBUTES lpSA
218 		);
219 	static PCREATEHARDLINKA pCreateHardLinkA;
220 	static int		tried;
221 	HMODULE			hDll;
222 	FARPROC			pfn;
223 	int			link_created;
224 	int			saved_errno;
225 
226 	if (!tried) {
227 		tried = TRUE;
228 		hDll = LoadLibrary("kernel32");
229 		pfn = GetProcAddress(hDll, "CreateHardLinkA");
230 		pCreateHardLinkA = (PCREATEHARDLINKA)pfn;
231 	}
232 
233 	if (NULL == pCreateHardLinkA) {
234 		errno = ENOSYS;
235 		return -1;
236 	}
237 
238 	link_created = (*pCreateHardLinkA)(linkname, filename, NULL);
239 
240 	if (link_created)
241 		return 0;
242 
243 	saved_errno = GetLastError();	/* yes we play loose */
244 	mfprintf(stderr, "Create hard link %s to %s failed: %m\n",
245 		 linkname, filename);
246 	errno = saved_errno;
247 	return -1;
248 }
249 
250 void
251 InitWin32Sockets() {
252 	WORD wVersionRequested;
253 	WSADATA wsaData;
254 	wVersionRequested = MAKEWORD(2,0);
255 	if (WSAStartup(wVersionRequested, &wsaData))
256 	{
257 		fprintf(stderr, "No useable winsock.dll\n");
258 		exit(1);
259 	}
260 }
261 #endif /* SYS_WINNT */
262 
263 
264 /*
265  * followlink() - replace filename with its target if symlink.
266  *
267  * Some readlink() implementations do not null-terminate the result.
268  */
269 void
270 followlink(
271 	char *	fname,
272 	size_t	bufsiz
273 	)
274 {
275 	int len;
276 
277 	REQUIRE(bufsiz > 0);
278 
279 	len = readlink(fname, fname, (int)bufsiz);
280 	if (len < 0 ) {
281 		fname[0] = '\0';
282 		return;
283 	}
284 	if (len > (int)bufsiz - 1)
285 		len = (int)bufsiz - 1;
286 	fname[len] = '\0';
287 }
288 
289 
290 /*
291  * Main program
292  */
293 int
294 main(
295 	int	argc,		/* command line options */
296 	char	**argv
297 	)
298 {
299 	struct timeval tv;	/* initialization vector */
300 	int	md5key = 0;	/* generate MD5 keys */
301 	int	optct;		/* option count */
302 #ifdef AUTOKEY
303 	X509	*cert = NULL;	/* X509 certificate */
304 	EVP_PKEY *pkey_host = NULL; /* host key */
305 	EVP_PKEY *pkey_sign = NULL; /* sign key */
306 	EVP_PKEY *pkey_iffkey = NULL; /* IFF sever keys */
307 	EVP_PKEY *pkey_gqkey = NULL; /* GQ server keys */
308 	EVP_PKEY *pkey_mvkey = NULL; /* MV trusted agen keys */
309 	EVP_PKEY *pkey_mvpar[MVMAX]; /* MV cleient keys */
310 	int	hostkey = 0;	/* generate RSA keys */
311 	int	iffkey = 0;	/* generate IFF keys */
312 	int	gqkey = 0;	/* generate GQ keys */
313 	int	mvkey = 0;	/* update MV keys */
314 	int	mvpar = 0;	/* generate MV parameters */
315 	char	*sign = NULL;	/* sign key */
316 	EVP_PKEY *pkey = NULL;	/* temp key */
317 	const EVP_MD *ectx;	/* EVP digest */
318 	char	pathbuf[MAXFILENAME + 1];
319 	const char *scheme = NULL; /* digest/signature scheme */
320 	const char *ciphername = NULL; /* to encrypt priv. key */
321 	const char *exten = NULL;	/* private extension */
322 	char	*grpkey = NULL;	/* identity extension */
323 	int	nid;		/* X509 digest/signature scheme */
324 	FILE	*fstr = NULL;	/* file handle */
325 	char	groupbuf[MAXHOSTNAME + 1];
326 	u_int	temp;
327 	BIO *	bp;
328 	int	i, cnt;
329 	char *	ptr;
330 #endif	/* AUTOKEY */
331 
332 	progname = argv[0];
333 
334 #ifdef SYS_WINNT
335 	/* Initialize before OpenSSL checks */
336 	InitWin32Sockets();
337 	if (!init_randfile())
338 		fprintf(stderr, "Unable to initialize .rnd file\n");
339 	ssl_applink();
340 #endif
341 
342 #ifdef OPENSSL
343 	ssl_check_version();
344 #endif	/* OPENSSL */
345 
346 	ntp_crypto_srandom();
347 
348 	/*
349 	 * Process options, initialize host name and timestamp.
350 	 * gethostname() won't null-terminate if hostname is exactly the
351 	 * length provided for the buffer.
352 	 */
353 	gethostname(hostbuf, sizeof(hostbuf) - 1);
354 	hostbuf[COUNTOF(hostbuf) - 1] = '\0';
355 	hostname = hostbuf;
356 	groupname = hostbuf;
357 	passwd1 = hostbuf;
358 	passwd2 = NULL;
359 	GETTIMEOFDAY(&tv, NULL);
360 	epoch = tv.tv_sec;
361 	fstamp = (u_int)(epoch + JAN_1970);
362 
363 	optct = ntpOptionProcess(&ntp_keygenOptions, argc, argv);
364 	argc -= optct;	// Just in case we care later.
365 	argv += optct;	// Just in case we care later.
366 
367 #ifdef OPENSSL
368 	if (SSLeay() == SSLEAY_VERSION_NUMBER)
369 		fprintf(stderr, "Using OpenSSL version %s\n",
370 			SSLeay_version(SSLEAY_VERSION));
371 	else
372 		fprintf(stderr, "Built against OpenSSL %s, using version %s\n",
373 			OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
374 #endif /* OPENSSL */
375 
376 	debug = OPT_VALUE_SET_DEBUG_LEVEL;
377 
378 	if (HAVE_OPT( MD5KEY ))
379 		md5key++;
380 #ifdef AUTOKEY
381 	if (HAVE_OPT( PASSWORD ))
382 		passwd1 = estrdup(OPT_ARG( PASSWORD ));
383 
384 	if (HAVE_OPT( EXPORT_PASSWD ))
385 		passwd2 = estrdup(OPT_ARG( EXPORT_PASSWD ));
386 
387 	if (HAVE_OPT( HOST_KEY ))
388 		hostkey++;
389 
390 	if (HAVE_OPT( SIGN_KEY ))
391 		sign = estrdup(OPT_ARG( SIGN_KEY ));
392 
393 	if (HAVE_OPT( GQ_PARAMS ))
394 		gqkey++;
395 
396 	if (HAVE_OPT( IFFKEY ))
397 		iffkey++;
398 
399 	if (HAVE_OPT( MV_PARAMS )) {
400 		mvkey++;
401 		nkeys = OPT_VALUE_MV_PARAMS;
402 	}
403 	if (HAVE_OPT( MV_KEYS )) {
404 		mvpar++;
405 		nkeys = OPT_VALUE_MV_KEYS;
406 	}
407 
408 	if (HAVE_OPT( IMBITS ))
409 		modulus2 = OPT_VALUE_IMBITS;
410 
411 	if (HAVE_OPT( MODULUS ))
412 		modulus = OPT_VALUE_MODULUS;
413 
414 	if (HAVE_OPT( CERTIFICATE ))
415 		scheme = OPT_ARG( CERTIFICATE );
416 
417 	if (HAVE_OPT( CIPHER ))
418 		ciphername = OPT_ARG( CIPHER );
419 
420 	if (HAVE_OPT( SUBJECT_NAME ))
421 		hostname = estrdup(OPT_ARG( SUBJECT_NAME ));
422 
423 	if (HAVE_OPT( IDENT ))
424 		groupname = estrdup(OPT_ARG( IDENT ));
425 
426 	if (HAVE_OPT( LIFETIME ))
427 		lifetime = OPT_VALUE_LIFETIME;
428 
429 	if (HAVE_OPT( PVT_CERT ))
430 		exten = EXT_KEY_PRIVATE;
431 
432 	if (HAVE_OPT( TRUSTED_CERT ))
433 		exten = EXT_KEY_TRUST;
434 
435 	/*
436 	 * Remove the group name from the hostname variable used
437 	 * in host and sign certificate file names.
438 	 */
439 	if (hostname != hostbuf)
440 		ptr = strchr(hostname, '@');
441 	else
442 		ptr = NULL;
443 	if (ptr != NULL) {
444 		*ptr = '\0';
445 		groupname = estrdup(ptr + 1);
446 		/* -s @group is equivalent to -i group, host unch. */
447 		if (ptr == hostname)
448 			hostname = hostbuf;
449 	}
450 
451 	/*
452 	 * Derive host certificate issuer/subject names from host name
453 	 * and optional group.  If no groupname is provided, the issuer
454 	 * and subject is the hostname with no '@group', and the
455 	 * groupname variable is pointed to hostname for use in IFF, GQ,
456 	 * and MV parameters file names.
457 	 */
458 	if (groupname == hostbuf) {
459 		certname = hostname;
460 	} else {
461 		snprintf(certnamebuf, sizeof(certnamebuf), "%s@%s",
462 			 hostname, groupname);
463 		certname = certnamebuf;
464 	}
465 
466 	/*
467 	 * Seed random number generator and grow weeds.
468 	 */
469 	ERR_load_crypto_strings();
470 	OpenSSL_add_all_algorithms();
471 	if (!RAND_status()) {
472 		if (RAND_file_name(pathbuf, sizeof(pathbuf)) == NULL) {
473 			fprintf(stderr, "RAND_file_name %s\n",
474 			    ERR_error_string(ERR_get_error(), NULL));
475 			exit (-1);
476 		}
477 		temp = RAND_load_file(pathbuf, -1);
478 		if (temp == 0) {
479 			fprintf(stderr,
480 			    "RAND_load_file %s not found or empty\n",
481 			    pathbuf);
482 			exit (-1);
483 		}
484 		fprintf(stderr,
485 		    "Random seed file %s %u bytes\n", pathbuf, temp);
486 		RAND_add(&epoch, sizeof(epoch), 4.0);
487 	}
488 #endif	/* AUTOKEY */
489 
490 	/*
491 	 * Create new unencrypted MD5 keys file if requested. If this
492 	 * option is selected, ignore all other options.
493 	 */
494 	if (md5key) {
495 		gen_md5("md5");
496 		exit (0);
497 	}
498 
499 #ifdef AUTOKEY
500 	/*
501 	 * Load previous certificate if available.
502 	 */
503 	snprintf(filename, sizeof(filename), "ntpkey_cert_%s", hostname);
504 	if ((fstr = fopen(filename, "r")) != NULL) {
505 		cert = PEM_read_X509(fstr, NULL, NULL, NULL);
506 		fclose(fstr);
507 	}
508 	if (cert != NULL) {
509 
510 		/*
511 		 * Extract subject name.
512 		 */
513 		X509_NAME_oneline(X509_get_subject_name(cert), groupbuf,
514 		    MAXFILENAME);
515 
516 		/*
517 		 * Extract digest/signature scheme.
518 		 */
519 		if (scheme == NULL) {
520 			nid = X509_get_signature_nid(cert);
521 			scheme = OBJ_nid2sn(nid);
522 		}
523 
524 		/*
525 		 * If a key_usage extension field is present, determine
526 		 * whether this is a trusted or private certificate.
527 		 */
528 		if (exten == NULL) {
529 			ptr = strstr(groupbuf, "CN=");
530 			cnt = X509_get_ext_count(cert);
531 			for (i = 0; i < cnt; i++) {
532 				X509_EXTENSION *ext;
533 				ASN1_OBJECT *obj;
534 
535 				ext = X509_get_ext(cert, i);
536 				obj = X509_EXTENSION_get_object(ext);
537 
538 				if (OBJ_obj2nid(obj) ==
539 				    NID_ext_key_usage) {
540 					bp = BIO_new(BIO_s_mem());
541 					X509V3_EXT_print(bp, ext, 0, 0);
542 					BIO_gets(bp, pathbuf,
543 					    MAXFILENAME);
544 					BIO_free(bp);
545 					if (strcmp(pathbuf,
546 					    "Trust Root") == 0)
547 						exten = EXT_KEY_TRUST;
548 					else if (strcmp(pathbuf,
549 					    "Private") == 0)
550 						exten = EXT_KEY_PRIVATE;
551 					certname = estrdup(ptr + 3);
552 				}
553 			}
554 		}
555 	}
556 	if (scheme == NULL)
557 		scheme = "RSA-MD5";
558 	if (ciphername == NULL)
559 		ciphername = "des-ede3-cbc";
560 	cipher = EVP_get_cipherbyname(ciphername);
561 	if (cipher == NULL) {
562 		fprintf(stderr, "Unknown cipher %s\n", ciphername);
563 		exit(-1);
564 	}
565 	fprintf(stderr, "Using host %s group %s\n", hostname,
566 	    groupname);
567 
568 	/*
569 	 * Create a new encrypted RSA host key file if requested;
570 	 * otherwise, look for an existing host key file. If not found,
571 	 * create a new encrypted RSA host key file. If that fails, go
572 	 * no further.
573 	 */
574 	if (hostkey)
575 		pkey_host = genkey("RSA", "host");
576 	if (pkey_host == NULL) {
577 		snprintf(filename, sizeof(filename), "ntpkey_host_%s", hostname);
578 		pkey_host = readkey(filename, passwd1, &fstamp, NULL);
579 		if (pkey_host != NULL) {
580 			followlink(filename, sizeof(filename));
581 			fprintf(stderr, "Using host key %s\n",
582 			    filename);
583 		} else {
584 			pkey_host = genkey("RSA", "host");
585 		}
586 	}
587 	if (pkey_host == NULL) {
588 		fprintf(stderr, "Generating host key fails\n");
589 		exit(-1);
590 	}
591 
592 	/*
593 	 * Create new encrypted RSA or DSA sign keys file if requested;
594 	 * otherwise, look for an existing sign key file. If not found,
595 	 * use the host key instead.
596 	 */
597 	if (sign != NULL)
598 		pkey_sign = genkey(sign, "sign");
599 	if (pkey_sign == NULL) {
600 		snprintf(filename, sizeof(filename), "ntpkey_sign_%s",
601 			 hostname);
602 		pkey_sign = readkey(filename, passwd1, &fstamp, NULL);
603 		if (pkey_sign != NULL) {
604 			followlink(filename, sizeof(filename));
605 			fprintf(stderr, "Using sign key %s\n",
606 			    filename);
607 		} else {
608 			pkey_sign = pkey_host;
609 			fprintf(stderr, "Using host key as sign key\n");
610 		}
611 	}
612 
613 	/*
614 	 * Create new encrypted GQ server keys file if requested;
615 	 * otherwise, look for an exisiting file. If found, fetch the
616 	 * public key for the certificate.
617 	 */
618 	if (gqkey)
619 		pkey_gqkey = gen_gqkey("gqkey");
620 	if (pkey_gqkey == NULL) {
621 		snprintf(filename, sizeof(filename), "ntpkey_gqkey_%s",
622 		    groupname);
623 		pkey_gqkey = readkey(filename, passwd1, &fstamp, NULL);
624 		if (pkey_gqkey != NULL) {
625 			followlink(filename, sizeof(filename));
626 			fprintf(stderr, "Using GQ parameters %s\n",
627 			    filename);
628 		}
629 	}
630 	if (pkey_gqkey != NULL) {
631 		RSA	*rsa;
632 		const BIGNUM *q;
633 
634 		rsa = EVP_PKEY_get0_RSA(pkey_gqkey);
635 		RSA_get0_factors(rsa, NULL, &q);
636 		grpkey = BN_bn2hex(q);
637 	}
638 
639 	/*
640 	 * Write the nonencrypted GQ client parameters to the stdout
641 	 * stream. The parameter file is the server key file with the
642 	 * private key obscured.
643 	 */
644 	if (pkey_gqkey != NULL && HAVE_OPT(ID_KEY)) {
645 		RSA	*rsa;
646 
647 		snprintf(filename, sizeof(filename),
648 		    "ntpkey_gqpar_%s.%u", groupname, fstamp);
649 		fprintf(stderr, "Writing GQ parameters %s to stdout\n",
650 		    filename);
651 		fprintf(stdout, "# %s\n# %s\n", filename,
652 		    ctime(&epoch));
653 		/* XXX: This modifies the private key and should probably use a
654 		 * copy of it instead. */
655 		rsa = EVP_PKEY_get0_RSA(pkey_gqkey);
656 		RSA_set0_factors(rsa, BN_dup(BN_value_one()), BN_dup(BN_value_one()));
657 		pkey = EVP_PKEY_new();
658 		EVP_PKEY_assign_RSA(pkey, rsa);
659 		PEM_write_PKCS8PrivateKey(stdout, pkey, NULL, NULL, 0,
660 		    NULL, NULL);
661 		fflush(stdout);
662 		if (debug)
663 			RSA_print_fp(stderr, rsa, 0);
664 	}
665 
666 	/*
667 	 * Write the encrypted GQ server keys to the stdout stream.
668 	 */
669 	if (pkey_gqkey != NULL && passwd2 != NULL) {
670 		RSA	*rsa;
671 
672 		snprintf(filename, sizeof(filename),
673 		    "ntpkey_gqkey_%s.%u", groupname, fstamp);
674 		fprintf(stderr, "Writing GQ keys %s to stdout\n",
675 		    filename);
676 		fprintf(stdout, "# %s\n# %s\n", filename,
677 		    ctime(&epoch));
678 		rsa = EVP_PKEY_get0_RSA(pkey_gqkey);
679 		pkey = EVP_PKEY_new();
680 		EVP_PKEY_assign_RSA(pkey, rsa);
681 		PEM_write_PKCS8PrivateKey(stdout, pkey, cipher, NULL, 0,
682 		    NULL, passwd2);
683 		fflush(stdout);
684 		if (debug)
685 			RSA_print_fp(stderr, rsa, 0);
686 	}
687 
688 	/*
689 	 * Create new encrypted IFF server keys file if requested;
690 	 * otherwise, look for existing file.
691 	 */
692 	if (iffkey)
693 		pkey_iffkey = gen_iffkey("iffkey");
694 	if (pkey_iffkey == NULL) {
695 		snprintf(filename, sizeof(filename), "ntpkey_iffkey_%s",
696 		    groupname);
697 		pkey_iffkey = readkey(filename, passwd1, &fstamp, NULL);
698 		if (pkey_iffkey != NULL) {
699 			followlink(filename, sizeof(filename));
700 			fprintf(stderr, "Using IFF keys %s\n",
701 			    filename);
702 		}
703 	}
704 
705 	/*
706 	 * Write the nonencrypted IFF client parameters to the stdout
707 	 * stream. The parameter file is the server key file with the
708 	 * private key obscured.
709 	 */
710 	if (pkey_iffkey != NULL && HAVE_OPT(ID_KEY)) {
711 		DSA	*dsa;
712 
713 		snprintf(filename, sizeof(filename),
714 		    "ntpkey_iffpar_%s.%u", groupname, fstamp);
715 		fprintf(stderr, "Writing IFF parameters %s to stdout\n",
716 		    filename);
717 		fprintf(stdout, "# %s\n# %s\n", filename,
718 		    ctime(&epoch));
719 		/* XXX: This modifies the private key and should probably use a
720 		 * copy of it instead. */
721 		dsa = EVP_PKEY_get0_DSA(pkey_iffkey);
722 		DSA_set0_key(dsa, NULL, BN_dup(BN_value_one()));
723 		pkey = EVP_PKEY_new();
724 		EVP_PKEY_assign_DSA(pkey, dsa);
725 		PEM_write_PKCS8PrivateKey(stdout, pkey, NULL, NULL, 0,
726 		    NULL, NULL);
727 		fflush(stdout);
728 		if (debug)
729 			DSA_print_fp(stderr, dsa, 0);
730 	}
731 
732 	/*
733 	 * Write the encrypted IFF server keys to the stdout stream.
734 	 */
735 	if (pkey_iffkey != NULL && passwd2 != NULL) {
736 		DSA	*dsa;
737 
738 		snprintf(filename, sizeof(filename),
739 		    "ntpkey_iffkey_%s.%u", groupname, fstamp);
740 		fprintf(stderr, "Writing IFF keys %s to stdout\n",
741 		    filename);
742 		fprintf(stdout, "# %s\n# %s\n", filename,
743 		    ctime(&epoch));
744 		dsa = EVP_PKEY_get0_DSA(pkey_iffkey);
745 		pkey = EVP_PKEY_new();
746 		EVP_PKEY_assign_DSA(pkey, dsa);
747 		PEM_write_PKCS8PrivateKey(stdout, pkey, cipher, NULL, 0,
748 		    NULL, passwd2);
749 		fflush(stdout);
750 		if (debug)
751 			DSA_print_fp(stderr, dsa, 0);
752 	}
753 
754 	/*
755 	 * Create new encrypted MV trusted-authority keys file if
756 	 * requested; otherwise, look for existing keys file.
757 	 */
758 	if (mvkey)
759 		pkey_mvkey = gen_mvkey("mv", pkey_mvpar);
760 	if (pkey_mvkey == NULL) {
761 		snprintf(filename, sizeof(filename), "ntpkey_mvta_%s",
762 		    groupname);
763 		pkey_mvkey = readkey(filename, passwd1, &fstamp,
764 		    pkey_mvpar);
765 		if (pkey_mvkey != NULL) {
766 			followlink(filename, sizeof(filename));
767 			fprintf(stderr, "Using MV keys %s\n",
768 			    filename);
769 		}
770 	}
771 
772 	/*
773 	 * Write the nonencrypted MV client parameters to the stdout
774 	 * stream. For the moment, we always use the client parameters
775 	 * associated with client key 1.
776 	 */
777 	if (pkey_mvkey != NULL && HAVE_OPT(ID_KEY)) {
778 		snprintf(filename, sizeof(filename),
779 		    "ntpkey_mvpar_%s.%u", groupname, fstamp);
780 		fprintf(stderr, "Writing MV parameters %s to stdout\n",
781 		    filename);
782 		fprintf(stdout, "# %s\n# %s\n", filename,
783 		    ctime(&epoch));
784 		pkey = pkey_mvpar[2];
785 		PEM_write_PKCS8PrivateKey(stdout, pkey, NULL, NULL, 0,
786 		    NULL, NULL);
787 		fflush(stdout);
788 		if (debug)
789 			DSA_print_fp(stderr, EVP_PKEY_get0_DSA(pkey), 0);
790 	}
791 
792 	/*
793 	 * Write the encrypted MV server keys to the stdout stream.
794 	 */
795 	if (pkey_mvkey != NULL && passwd2 != NULL) {
796 		snprintf(filename, sizeof(filename),
797 		    "ntpkey_mvkey_%s.%u", groupname, fstamp);
798 		fprintf(stderr, "Writing MV keys %s to stdout\n",
799 		    filename);
800 		fprintf(stdout, "# %s\n# %s\n", filename,
801 		    ctime(&epoch));
802 		pkey = pkey_mvpar[1];
803 		PEM_write_PKCS8PrivateKey(stdout, pkey, cipher, NULL, 0,
804 		    NULL, passwd2);
805 		fflush(stdout);
806 		if (debug)
807 			DSA_print_fp(stderr, EVP_PKEY_get0_DSA(pkey), 0);
808 	}
809 
810 	/*
811 	 * Decode the digest/signature scheme and create the
812 	 * certificate. Do this every time we run the program.
813 	 */
814 	ectx = EVP_get_digestbyname(scheme);
815 	if (ectx == NULL) {
816 		fprintf(stderr,
817 		    "Invalid digest/signature combination %s\n",
818 		    scheme);
819 			exit (-1);
820 	}
821 	x509(pkey_sign, ectx, grpkey, exten, certname);
822 #endif	/* AUTOKEY */
823 	exit(0);
824 }
825 
826 
827 /*
828  * Generate semi-random MD5 keys compatible with NTPv3 and NTPv4. Also,
829  * if OpenSSL is around, generate random SHA1 keys compatible with
830  * symmetric key cryptography.
831  */
832 int
833 gen_md5(
834 	const char *id		/* file name id */
835 	)
836 {
837 	u_char	md5key[MD5SIZE + 1];	/* MD5 key */
838 	FILE	*str;
839 	int	i, j;
840 #ifdef OPENSSL
841 	u_char	keystr[MD5SIZE];
842 	u_char	hexstr[2 * MD5SIZE + 1];
843 	u_char	hex[] = "0123456789abcdef";
844 #endif	/* OPENSSL */
845 
846 	str = fheader("MD5key", id, groupname);
847 	for (i = 1; i <= MD5KEYS; i++) {
848 		for (j = 0; j < MD5SIZE; j++) {
849 			u_char temp;
850 
851 			while (1) {
852 				int rc;
853 
854 				rc = ntp_crypto_random_buf(
855 				    &temp, sizeof(temp));
856 				if (-1 == rc) {
857 					fprintf(stderr, "ntp_crypto_random_buf() failed.\n");
858 					exit (-1);
859 				}
860 				if (temp == '#')
861 					continue;
862 
863 				if (temp > 0x20 && temp < 0x7f)
864 					break;
865 			}
866 			md5key[j] = temp;
867 		}
868 		md5key[j] = '\0';
869 		fprintf(str, "%2d MD5 %s  # MD5 key\n", i,
870 		    md5key);
871 	}
872 #ifdef OPENSSL
873 	for (i = 1; i <= MD5KEYS; i++) {
874 		RAND_bytes(keystr, 20);
875 		for (j = 0; j < MD5SIZE; j++) {
876 			hexstr[2 * j] = hex[keystr[j] >> 4];
877 			hexstr[2 * j + 1] = hex[keystr[j] & 0xf];
878 		}
879 		hexstr[2 * MD5SIZE] = '\0';
880 		fprintf(str, "%2d SHA1 %s  # SHA1 key\n", i + MD5KEYS,
881 		    hexstr);
882 	}
883 #endif	/* OPENSSL */
884 	fclose(str);
885 	return (1);
886 }
887 
888 
889 #ifdef AUTOKEY
890 /*
891  * readkey - load cryptographic parameters and keys
892  *
893  * This routine loads a PEM-encoded file of given name and password and
894  * extracts the filestamp from the file name. It returns a pointer to
895  * the first key if valid, NULL if not.
896  */
897 EVP_PKEY *			/* public/private key pair */
898 readkey(
899 	char	*cp,		/* file name */
900 	char	*passwd,	/* password */
901 	u_int	*estamp,	/* file stamp */
902 	EVP_PKEY **evpars	/* parameter list pointer */
903 	)
904 {
905 	FILE	*str;		/* file handle */
906 	EVP_PKEY *pkey = NULL;	/* public/private key */
907 	u_int	gstamp;		/* filestamp */
908 	char	linkname[MAXFILENAME]; /* filestamp buffer) */
909 	EVP_PKEY *parkey;
910 	char	*ptr;
911 	int	i;
912 
913 	/*
914 	 * Open the key file.
915 	 */
916 	str = fopen(cp, "r");
917 	if (str == NULL)
918 		return (NULL);
919 
920 	/*
921 	 * Read the filestamp, which is contained in the first line.
922 	 */
923 	if ((ptr = fgets(linkname, MAXFILENAME, str)) == NULL) {
924 		fprintf(stderr, "Empty key file %s\n", cp);
925 		fclose(str);
926 		return (NULL);
927 	}
928 	if ((ptr = strrchr(ptr, '.')) == NULL) {
929 		fprintf(stderr, "No filestamp found in %s\n", cp);
930 		fclose(str);
931 		return (NULL);
932 	}
933 	if (sscanf(++ptr, "%u", &gstamp) != 1) {
934 		fprintf(stderr, "Invalid filestamp found in %s\n", cp);
935 		fclose(str);
936 		return (NULL);
937 	}
938 
939 	/*
940 	 * Read and decrypt PEM-encoded private keys. The first one
941 	 * found is returned. If others are expected, add them to the
942 	 * parameter list.
943 	 */
944 	for (i = 0; i <= MVMAX - 1;) {
945 		parkey = PEM_read_PrivateKey(str, NULL, NULL, passwd);
946 		if (evpars != NULL) {
947 			evpars[i++] = parkey;
948 			evpars[i] = NULL;
949 		}
950 		if (parkey == NULL)
951 			break;
952 
953 		if (pkey == NULL)
954 			pkey = parkey;
955 		if (debug) {
956 			if (EVP_PKEY_base_id(parkey) == EVP_PKEY_DSA)
957 				DSA_print_fp(stderr, EVP_PKEY_get0_DSA(parkey),
958 				    0);
959 			else if (EVP_PKEY_base_id(parkey) == EVP_PKEY_RSA)
960 				RSA_print_fp(stderr, EVP_PKEY_get0_RSA(parkey),
961 				    0);
962 		}
963 	}
964 	fclose(str);
965 	if (pkey == NULL) {
966 		fprintf(stderr, "Corrupt file %s or wrong key %s\n%s\n",
967 		    cp, passwd, ERR_error_string(ERR_get_error(),
968 		    NULL));
969 		exit (-1);
970 	}
971 	*estamp = gstamp;
972 	return (pkey);
973 }
974 
975 
976 /*
977  * Generate RSA public/private key pair
978  */
979 EVP_PKEY *			/* public/private key pair */
980 gen_rsa(
981 	const char *id		/* file name id */
982 	)
983 {
984 	EVP_PKEY *pkey;		/* private key */
985 	RSA	*rsa;		/* RSA parameters and key pair */
986 	FILE	*str;
987 
988 	fprintf(stderr, "Generating RSA keys (%d bits)...\n", modulus);
989 	rsa = genRsaKeyPair(modulus, _UC("RSA"));
990 	fprintf(stderr, "\n");
991 	if (rsa == NULL) {
992 		fprintf(stderr, "RSA generate keys fails\n%s\n",
993 		    ERR_error_string(ERR_get_error(), NULL));
994 		return (NULL);
995 	}
996 
997 	/*
998 	 * For signature encryption it is not necessary that the RSA
999 	 * parameters be strictly groomed and once in a while the
1000 	 * modulus turns out to be non-prime. Just for grins, we check
1001 	 * the primality.
1002 	 */
1003 	if (!RSA_check_key(rsa)) {
1004 		fprintf(stderr, "Invalid RSA key\n%s\n",
1005 		    ERR_error_string(ERR_get_error(), NULL));
1006 		RSA_free(rsa);
1007 		return (NULL);
1008 	}
1009 
1010 	/*
1011 	 * Write the RSA parameters and keys as a RSA private key
1012 	 * encoded in PEM.
1013 	 */
1014 	if (strcmp(id, "sign") == 0)
1015 		str = fheader("RSAsign", id, hostname);
1016 	else
1017 		str = fheader("RSAhost", id, hostname);
1018 	pkey = EVP_PKEY_new();
1019 	EVP_PKEY_assign_RSA(pkey, rsa);
1020 	PEM_write_PKCS8PrivateKey(str, pkey, cipher, NULL, 0, NULL,
1021 	    passwd1);
1022 	fclose(str);
1023 	if (debug)
1024 		RSA_print_fp(stderr, rsa, 0);
1025 	return (pkey);
1026 }
1027 
1028 
1029 /*
1030  * Generate DSA public/private key pair
1031  */
1032 EVP_PKEY *			/* public/private key pair */
1033 gen_dsa(
1034 	const char *id		/* file name id */
1035 	)
1036 {
1037 	EVP_PKEY *pkey;		/* private key */
1038 	DSA	*dsa;		/* DSA parameters */
1039 	FILE	*str;
1040 
1041 	/*
1042 	 * Generate DSA parameters.
1043 	 */
1044 	fprintf(stderr,
1045 	    "Generating DSA parameters (%d bits)...\n", modulus);
1046 	dsa = genDsaParams(modulus, _UC("DSA"));
1047 	fprintf(stderr, "\n");
1048 	if (dsa == NULL) {
1049 		fprintf(stderr, "DSA generate parameters fails\n%s\n",
1050 		    ERR_error_string(ERR_get_error(), NULL));
1051 		return (NULL);
1052 	}
1053 
1054 	/*
1055 	 * Generate DSA keys.
1056 	 */
1057 	fprintf(stderr, "Generating DSA keys (%d bits)...\n", modulus);
1058 	if (!DSA_generate_key(dsa)) {
1059 		fprintf(stderr, "DSA generate keys fails\n%s\n",
1060 		    ERR_error_string(ERR_get_error(), NULL));
1061 		DSA_free(dsa);
1062 		return (NULL);
1063 	}
1064 
1065 	/*
1066 	 * Write the DSA parameters and keys as a DSA private key
1067 	 * encoded in PEM.
1068 	 */
1069 	str = fheader("DSAsign", id, hostname);
1070 	pkey = EVP_PKEY_new();
1071 	EVP_PKEY_assign_DSA(pkey, dsa);
1072 	PEM_write_PKCS8PrivateKey(str, pkey, cipher, NULL, 0, NULL,
1073 	    passwd1);
1074 	fclose(str);
1075 	if (debug)
1076 		DSA_print_fp(stderr, dsa, 0);
1077 	return (pkey);
1078 }
1079 
1080 
1081 /*
1082  ***********************************************************************
1083  *								       *
1084  * The following routines implement the Schnorr (IFF) identity scheme  *
1085  *								       *
1086  ***********************************************************************
1087  *
1088  * The Schnorr (IFF) identity scheme is intended for use when
1089  * certificates are generated by some other trusted certificate
1090  * authority and the certificate cannot be used to convey public
1091  * parameters. There are two kinds of files: encrypted server files that
1092  * contain private and public values and nonencrypted client files that
1093  * contain only public values. New generations of server files must be
1094  * securely transmitted to all servers of the group; client files can be
1095  * distributed by any means. The scheme is self contained and
1096  * independent of new generations of host keys, sign keys and
1097  * certificates.
1098  *
1099  * The IFF values hide in a DSA cuckoo structure which uses the same
1100  * parameters. The values are used by an identity scheme based on DSA
1101  * cryptography and described in Stimson p. 285. The p is a 512-bit
1102  * prime, g a generator of Zp* and q a 160-bit prime that divides p - 1
1103  * and is a qth root of 1 mod p; that is, g^q = 1 mod p. The TA rolls a
1104  * private random group key b (0 < b < q) and public key v = g^b, then
1105  * sends (p, q, g, b) to the servers and (p, q, g, v) to the clients.
1106  * Alice challenges Bob to confirm identity using the protocol described
1107  * below.
1108  *
1109  * How it works
1110  *
1111  * The scheme goes like this. Both Alice and Bob have the public primes
1112  * p, q and generator g. The TA gives private key b to Bob and public
1113  * key v to Alice.
1114  *
1115  * Alice rolls new random challenge r (o < r < q) and sends to Bob in
1116  * the IFF request message. Bob rolls new random k (0 < k < q), then
1117  * computes y = k + b r mod q and x = g^k mod p and sends (y, hash(x))
1118  * to Alice in the response message. Besides making the response
1119  * shorter, the hash makes it effectivey impossible for an intruder to
1120  * solve for b by observing a number of these messages.
1121  *
1122  * Alice receives the response and computes g^y v^r mod p. After a bit
1123  * of algebra, this simplifies to g^k. If the hash of this result
1124  * matches hash(x), Alice knows that Bob has the group key b. The signed
1125  * response binds this knowledge to Bob's private key and the public key
1126  * previously received in his certificate.
1127  */
1128 /*
1129  * Generate Schnorr (IFF) keys.
1130  */
1131 EVP_PKEY *			/* DSA cuckoo nest */
1132 gen_iffkey(
1133 	const char *id		/* file name id */
1134 	)
1135 {
1136 	EVP_PKEY *pkey;		/* private key */
1137 	DSA	*dsa;		/* DSA parameters */
1138 	BN_CTX	*ctx;		/* BN working space */
1139 	BIGNUM	*b, *r, *k, *u, *v, *w; /* BN temp */
1140 	FILE	*str;
1141 	u_int	temp;
1142 	const BIGNUM *p, *q, *g;
1143 	BIGNUM *pub_key, *priv_key;
1144 
1145 	/*
1146 	 * Generate DSA parameters for use as IFF parameters.
1147 	 */
1148 	fprintf(stderr, "Generating IFF keys (%d bits)...\n",
1149 	    modulus2);
1150 	dsa = genDsaParams(modulus2, _UC("IFF"));
1151 	fprintf(stderr, "\n");
1152 	if (dsa == NULL) {
1153 		fprintf(stderr, "DSA generate parameters fails\n%s\n",
1154 		    ERR_error_string(ERR_get_error(), NULL));
1155 		return (NULL);
1156 	}
1157 	DSA_get0_pqg(dsa, &p, &q, &g);
1158 
1159 	/*
1160 	 * Generate the private and public keys. The DSA parameters and
1161 	 * private key are distributed to the servers, while all except
1162 	 * the private key are distributed to the clients.
1163 	 */
1164 	b = BN_new(); r = BN_new(); k = BN_new();
1165 	u = BN_new(); v = BN_new(); w = BN_new(); ctx = BN_CTX_new();
1166 	BN_rand(b, BN_num_bits(q), -1, 0);	/* a */
1167 	BN_mod(b, b, q, ctx);
1168 	BN_sub(v, q, b);
1169 	BN_mod_exp(v, g, v, p, ctx); /* g^(q - b) mod p */
1170 	BN_mod_exp(u, g, b, p, ctx);	/* g^b mod p */
1171 	BN_mod_mul(u, u, v, p, ctx);
1172 	temp = BN_is_one(u);
1173 	fprintf(stderr,
1174 	    "Confirm g^(q - b) g^b = 1 mod p: %s\n", temp == 1 ?
1175 	    "yes" : "no");
1176 	if (!temp) {
1177 		BN_free(b); BN_free(r); BN_free(k);
1178 		BN_free(u); BN_free(v); BN_free(w); BN_CTX_free(ctx);
1179 		return (NULL);
1180 	}
1181 	pub_key = BN_dup(v);
1182 	priv_key = BN_dup(b);
1183 	DSA_set0_key(dsa, pub_key, priv_key);
1184 
1185 	/*
1186 	 * Here is a trial round of the protocol. First, Alice rolls
1187 	 * random nonce r mod q and sends it to Bob. She needs only
1188 	 * q from parameters.
1189 	 */
1190 	BN_rand(r, BN_num_bits(q), -1, 0);	/* r */
1191 	BN_mod(r, r, q, ctx);
1192 
1193 	/*
1194 	 * Bob rolls random nonce k mod q, computes y = k + b r mod q
1195 	 * and x = g^k mod p, then sends (y, x) to Alice. He needs
1196 	 * p, q and b from parameters and r from Alice.
1197 	 */
1198 	BN_rand(k, BN_num_bits(q), -1, 0);	/* k, 0 < k < q  */
1199 	BN_mod(k, k, q, ctx);
1200 	BN_mod_mul(v, priv_key, r, q, ctx); /* b r mod q */
1201 	BN_add(v, v, k);
1202 	BN_mod(v, v, q, ctx);		/* y = k + b r mod q */
1203 	BN_mod_exp(u, g, k, p, ctx);	/* x = g^k mod p */
1204 
1205 	/*
1206 	 * Alice verifies x = g^y v^r to confirm that Bob has group key
1207 	 * b. She needs p, q, g from parameters, (y, x) from Bob and the
1208 	 * original r. We omit the detail here thatt only the hash of y
1209 	 * is sent.
1210 	 */
1211 	BN_mod_exp(v, g, v, p, ctx); /* g^y mod p */
1212 	BN_mod_exp(w, pub_key, r, p, ctx); /* v^r */
1213 	BN_mod_mul(v, w, v, p, ctx);	/* product mod p */
1214 	temp = BN_cmp(u, v);
1215 	fprintf(stderr,
1216 	    "Confirm g^k = g^(k + b r) g^(q - b) r: %s\n", temp ==
1217 	    0 ? "yes" : "no");
1218 	BN_free(b); BN_free(r);	BN_free(k);
1219 	BN_free(u); BN_free(v); BN_free(w); BN_CTX_free(ctx);
1220 	if (temp != 0) {
1221 		DSA_free(dsa);
1222 		return (NULL);
1223 	}
1224 
1225 	/*
1226 	 * Write the IFF keys as an encrypted DSA private key encoded in
1227 	 * PEM.
1228 	 *
1229 	 * p	modulus p
1230 	 * q	modulus q
1231 	 * g	generator g
1232 	 * priv_key b
1233 	 * public_key v
1234 	 * kinv	not used
1235 	 * r	not used
1236 	 */
1237 	str = fheader("IFFkey", id, groupname);
1238 	pkey = EVP_PKEY_new();
1239 	EVP_PKEY_assign_DSA(pkey, dsa);
1240 	PEM_write_PKCS8PrivateKey(str, pkey, cipher, NULL, 0, NULL,
1241 	    passwd1);
1242 	fclose(str);
1243 	if (debug)
1244 		DSA_print_fp(stderr, dsa, 0);
1245 	return (pkey);
1246 }
1247 
1248 
1249 /*
1250  ***********************************************************************
1251  *								       *
1252  * The following routines implement the Guillou-Quisquater (GQ)        *
1253  * identity scheme                                                     *
1254  *								       *
1255  ***********************************************************************
1256  *
1257  * The Guillou-Quisquater (GQ) identity scheme is intended for use when
1258  * the certificate can be used to convey public parameters. The scheme
1259  * uses a X509v3 certificate extension field do convey the public key of
1260  * a private key known only to servers. There are two kinds of files:
1261  * encrypted server files that contain private and public values and
1262  * nonencrypted client files that contain only public values. New
1263  * generations of server files must be securely transmitted to all
1264  * servers of the group; client files can be distributed by any means.
1265  * The scheme is self contained and independent of new generations of
1266  * host keys and sign keys. The scheme is self contained and independent
1267  * of new generations of host keys and sign keys.
1268  *
1269  * The GQ parameters hide in a RSA cuckoo structure which uses the same
1270  * parameters. The values are used by an identity scheme based on RSA
1271  * cryptography and described in Stimson p. 300 (with errors). The 512-
1272  * bit public modulus is n = p q, where p and q are secret large primes.
1273  * The TA rolls private random group key b as RSA exponent. These values
1274  * are known to all group members.
1275  *
1276  * When rolling new certificates, a server recomputes the private and
1277  * public keys. The private key u is a random roll, while the public key
1278  * is the inverse obscured by the group key v = (u^-1)^b. These values
1279  * replace the private and public keys normally generated by the RSA
1280  * scheme. Alice challenges Bob to confirm identity using the protocol
1281  * described below.
1282  *
1283  * How it works
1284  *
1285  * The scheme goes like this. Both Alice and Bob have the same modulus n
1286  * and some random b as the group key. These values are computed and
1287  * distributed in advance via secret means, although only the group key
1288  * b is truly secret. Each has a private random private key u and public
1289  * key (u^-1)^b, although not necessarily the same ones. Bob and Alice
1290  * can regenerate the key pair from time to time without affecting
1291  * operations. The public key is conveyed on the certificate in an
1292  * extension field; the private key is never revealed.
1293  *
1294  * Alice rolls new random challenge r and sends to Bob in the GQ
1295  * request message. Bob rolls new random k, then computes y = k u^r mod
1296  * n and x = k^b mod n and sends (y, hash(x)) to Alice in the response
1297  * message. Besides making the response shorter, the hash makes it
1298  * effectivey impossible for an intruder to solve for b by observing
1299  * a number of these messages.
1300  *
1301  * Alice receives the response and computes y^b v^r mod n. After a bit
1302  * of algebra, this simplifies to k^b. If the hash of this result
1303  * matches hash(x), Alice knows that Bob has the group key b. The signed
1304  * response binds this knowledge to Bob's private key and the public key
1305  * previously received in his certificate.
1306  */
1307 /*
1308  * Generate Guillou-Quisquater (GQ) parameters file.
1309  */
1310 EVP_PKEY *			/* RSA cuckoo nest */
1311 gen_gqkey(
1312 	const char *id		/* file name id */
1313 	)
1314 {
1315 	EVP_PKEY *pkey;		/* private key */
1316 	RSA	*rsa;		/* RSA parameters */
1317 	BN_CTX	*ctx;		/* BN working space */
1318 	BIGNUM	*u, *v, *g, *k, *r, *y; /* BN temps */
1319 	FILE	*str;
1320 	u_int	temp;
1321 	BIGNUM	*b;
1322 	const BIGNUM	*n;
1323 
1324 	/*
1325 	 * Generate RSA parameters for use as GQ parameters.
1326 	 */
1327 	fprintf(stderr,
1328 	    "Generating GQ parameters (%d bits)...\n",
1329 	     modulus2);
1330 	rsa = genRsaKeyPair(modulus2, _UC("GQ"));
1331 	fprintf(stderr, "\n");
1332 	if (rsa == NULL) {
1333 		fprintf(stderr, "RSA generate keys fails\n%s\n",
1334 		    ERR_error_string(ERR_get_error(), NULL));
1335 		return (NULL);
1336 	}
1337 	RSA_get0_key(rsa, &n, NULL, NULL);
1338 	u = BN_new(); v = BN_new(); g = BN_new();
1339 	k = BN_new(); r = BN_new(); y = BN_new();
1340 	b = BN_new();
1341 
1342 	/*
1343 	 * Generate the group key b, which is saved in the e member of
1344 	 * the RSA structure. The group key is transmitted to each group
1345 	 * member encrypted by the member private key.
1346 	 */
1347 	ctx = BN_CTX_new();
1348 	BN_rand(b, BN_num_bits(n), -1, 0); /* b */
1349 	BN_mod(b, b, n, ctx);
1350 
1351 	/*
1352 	 * When generating his certificate, Bob rolls random private key
1353 	 * u, then computes inverse v = u^-1.
1354 	 */
1355 	BN_rand(u, BN_num_bits(n), -1, 0); /* u */
1356 	BN_mod(u, u, n, ctx);
1357 	BN_mod_inverse(v, u, n, ctx);	/* u^-1 mod n */
1358 	BN_mod_mul(k, v, u, n, ctx);
1359 
1360 	/*
1361 	 * Bob computes public key v = (u^-1)^b, which is saved in an
1362 	 * extension field on his certificate. We check that u^b v =
1363 	 * 1 mod n.
1364 	 */
1365 	BN_mod_exp(v, v, b, n, ctx);
1366 	BN_mod_exp(g, u, b, n, ctx); /* u^b */
1367 	BN_mod_mul(g, g, v, n, ctx); /* u^b (u^-1)^b */
1368 	temp = BN_is_one(g);
1369 	fprintf(stderr,
1370 	    "Confirm u^b (u^-1)^b = 1 mod n: %s\n", temp ? "yes" :
1371 	    "no");
1372 	if (!temp) {
1373 		BN_free(u); BN_free(v);
1374 		BN_free(g); BN_free(k); BN_free(r); BN_free(y);
1375 		BN_CTX_free(ctx);
1376 		RSA_free(rsa);
1377 		return (NULL);
1378 	}
1379 	/* setting 'u' and 'v' into a RSA object takes over ownership.
1380 	 * Since we use these values again, we have to pass in dupes,
1381 	 * or we'll corrupt the program!
1382 	 */
1383 	RSA_set0_factors(rsa, BN_dup(u), BN_dup(v));
1384 
1385 	/*
1386 	 * Here is a trial run of the protocol. First, Alice rolls
1387 	 * random nonce r mod n and sends it to Bob. She needs only n
1388 	 * from parameters.
1389 	 */
1390 	BN_rand(r, BN_num_bits(n), -1, 0);	/* r */
1391 	BN_mod(r, r, n, ctx);
1392 
1393 	/*
1394 	 * Bob rolls random nonce k mod n, computes y = k u^r mod n and
1395 	 * g = k^b mod n, then sends (y, g) to Alice. He needs n, u, b
1396 	 * from parameters and r from Alice.
1397 	 */
1398 	BN_rand(k, BN_num_bits(n), -1, 0);	/* k */
1399 	BN_mod(k, k, n, ctx);
1400 	BN_mod_exp(y, u, r, n, ctx);	/* u^r mod n */
1401 	BN_mod_mul(y, k, y, n, ctx);	/* y = k u^r mod n */
1402 	BN_mod_exp(g, k, b, n, ctx);	/* g = k^b mod n */
1403 
1404 	/*
1405 	 * Alice verifies g = v^r y^b mod n to confirm that Bob has
1406 	 * private key u. She needs n, g from parameters, public key v =
1407 	 * (u^-1)^b from the certificate, (y, g) from Bob and the
1408 	 * original r. We omit the detaul here that only the hash of g
1409 	 * is sent.
1410 	 */
1411 	BN_mod_exp(v, v, r, n, ctx);	/* v^r mod n */
1412 	BN_mod_exp(y, y, b, n, ctx);	/* y^b mod n */
1413 	BN_mod_mul(y, v, y, n, ctx);	/* v^r y^b mod n */
1414 	temp = BN_cmp(y, g);
1415 	fprintf(stderr, "Confirm g^k = v^r y^b mod n: %s\n", temp == 0 ?
1416 	    "yes" : "no");
1417 	BN_CTX_free(ctx); BN_free(u); BN_free(v);
1418 	BN_free(g); BN_free(k); BN_free(r); BN_free(y);
1419 	if (temp != 0) {
1420 		RSA_free(rsa);
1421 		return (NULL);
1422 	}
1423 
1424 	/*
1425 	 * Write the GQ parameter file as an encrypted RSA private key
1426 	 * encoded in PEM.
1427 	 *
1428 	 * n	modulus n
1429 	 * e	group key b
1430 	 * d	not used
1431 	 * p	private key u
1432 	 * q	public key (u^-1)^b
1433 	 * dmp1	not used
1434 	 * dmq1	not used
1435 	 * iqmp	not used
1436 	 */
1437 	RSA_set0_key(rsa, NULL, b, BN_dup(BN_value_one()));
1438 	RSA_set0_crt_params(rsa, BN_dup(BN_value_one()), BN_dup(BN_value_one()),
1439 		BN_dup(BN_value_one()));
1440 	str = fheader("GQkey", id, groupname);
1441 	pkey = EVP_PKEY_new();
1442 	EVP_PKEY_assign_RSA(pkey, rsa);
1443 	PEM_write_PKCS8PrivateKey(str, pkey, cipher, NULL, 0, NULL,
1444 	    passwd1);
1445 	fclose(str);
1446 	if (debug)
1447 		RSA_print_fp(stderr, rsa, 0);
1448 	return (pkey);
1449 }
1450 
1451 
1452 /*
1453  ***********************************************************************
1454  *								       *
1455  * The following routines implement the Mu-Varadharajan (MV) identity  *
1456  * scheme                                                              *
1457  *								       *
1458  ***********************************************************************
1459  *
1460  * The Mu-Varadharajan (MV) cryptosystem was originally intended when
1461  * servers broadcast messages to clients, but clients never send
1462  * messages to servers. There is one encryption key for the server and a
1463  * separate decryption key for each client. It operated something like a
1464  * pay-per-view satellite broadcasting system where the session key is
1465  * encrypted by the broadcaster and the decryption keys are held in a
1466  * tamperproof set-top box.
1467  *
1468  * The MV parameters and private encryption key hide in a DSA cuckoo
1469  * structure which uses the same parameters, but generated in a
1470  * different way. The values are used in an encryption scheme similar to
1471  * El Gamal cryptography and a polynomial formed from the expansion of
1472  * product terms (x - x[j]), as described in Mu, Y., and V.
1473  * Varadharajan: Robust and Secure Broadcasting, Proc. Indocrypt 2001,
1474  * 223-231. The paper has significant errors and serious omissions.
1475  *
1476  * Let q be the product of n distinct primes s1[j] (j = 1...n), where
1477  * each s1[j] has m significant bits. Let p be a prime p = 2 * q + 1, so
1478  * that q and each s1[j] divide p - 1 and p has M = n * m + 1
1479  * significant bits. Let g be a generator of Zp; that is, gcd(g, p - 1)
1480  * = 1 and g^q = 1 mod p. We do modular arithmetic over Zq and then
1481  * project into Zp* as exponents of g. Sometimes we have to compute an
1482  * inverse b^-1 of random b in Zq, but for that purpose we require
1483  * gcd(b, q) = 1. We expect M to be in the 500-bit range and n
1484  * relatively small, like 30. These are the parameters of the scheme and
1485  * they are expensive to compute.
1486  *
1487  * We set up an instance of the scheme as follows. A set of random
1488  * values x[j] mod q (j = 1...n), are generated as the zeros of a
1489  * polynomial of order n. The product terms (x - x[j]) are expanded to
1490  * form coefficients a[i] mod q (i = 0...n) in powers of x. These are
1491  * used as exponents of the generator g mod p to generate the private
1492  * encryption key A. The pair (gbar, ghat) of public server keys and the
1493  * pairs (xbar[j], xhat[j]) (j = 1...n) of private client keys are used
1494  * to construct the decryption keys. The devil is in the details.
1495  *
1496  * This routine generates a private server encryption file including the
1497  * private encryption key E and partial decryption keys gbar and ghat.
1498  * It then generates public client decryption files including the public
1499  * keys xbar[j] and xhat[j] for each client j. The partial decryption
1500  * files are used to compute the inverse of E. These values are suitably
1501  * blinded so secrets are not revealed.
1502  *
1503  * The distinguishing characteristic of this scheme is the capability to
1504  * revoke keys. Included in the calculation of E, gbar and ghat is the
1505  * product s = prod(s1[j]) (j = 1...n) above. If the factor s1[j] is
1506  * subsequently removed from the product and E, gbar and ghat
1507  * recomputed, the jth client will no longer be able to compute E^-1 and
1508  * thus unable to decrypt the messageblock.
1509  *
1510  * How it works
1511  *
1512  * The scheme goes like this. Bob has the server values (p, E, q,
1513  * gbar, ghat) and Alice has the client values (p, xbar, xhat).
1514  *
1515  * Alice rolls new random nonce r mod p and sends to Bob in the MV
1516  * request message. Bob rolls random nonce k mod q, encrypts y = r E^k
1517  * mod p and sends (y, gbar^k, ghat^k) to Alice.
1518  *
1519  * Alice receives the response and computes the inverse (E^k)^-1 from
1520  * the partial decryption keys gbar^k, ghat^k, xbar and xhat. She then
1521  * decrypts y and verifies it matches the original r. The signed
1522  * response binds this knowledge to Bob's private key and the public key
1523  * previously received in his certificate.
1524  */
1525 EVP_PKEY *			/* DSA cuckoo nest */
1526 gen_mvkey(
1527 	const char *id,		/* file name id */
1528 	EVP_PKEY **evpars	/* parameter list pointer */
1529 	)
1530 {
1531 	EVP_PKEY *pkey, *pkey1;	/* private keys */
1532 	DSA	*dsa, *dsa2, *sdsa; /* DSA parameters */
1533 	BN_CTX	*ctx;		/* BN working space */
1534 	BIGNUM	*a[MVMAX];	/* polynomial coefficient vector */
1535 	BIGNUM	*gs[MVMAX];	/* public key vector */
1536 	BIGNUM	*s1[MVMAX];	/* private enabling keys */
1537 	BIGNUM	*x[MVMAX];	/* polynomial zeros vector */
1538 	BIGNUM	*xbar[MVMAX], *xhat[MVMAX]; /* private keys vector */
1539 	BIGNUM	*b;		/* group key */
1540 	BIGNUM	*b1;		/* inverse group key */
1541 	BIGNUM	*s;		/* enabling key */
1542 	BIGNUM	*biga;		/* master encryption key */
1543 	BIGNUM	*bige;		/* session encryption key */
1544 	BIGNUM	*gbar, *ghat;	/* public key */
1545 	BIGNUM	*u, *v, *w;	/* BN scratch */
1546 	BIGNUM	*p, *q, *g, *priv_key, *pub_key;
1547 	int	i, j, n;
1548 	FILE	*str;
1549 	u_int	temp;
1550 
1551 	/*
1552 	 * Generate MV parameters.
1553 	 *
1554 	 * The object is to generate a multiplicative group Zp* modulo a
1555 	 * prime p and a subset Zq mod q, where q is the product of n
1556 	 * distinct primes s1[j] (j = 1...n) and q divides p - 1. We
1557 	 * first generate n m-bit primes, where the product n m is in
1558 	 * the order of 512 bits. One or more of these may have to be
1559 	 * replaced later. As a practical matter, it is tough to find
1560 	 * more than 31 distinct primes for 512 bits or 61 primes for
1561 	 * 1024 bits. The latter can take several hundred iterations
1562 	 * and several minutes on a Sun Blade 1000.
1563 	 */
1564 	n = nkeys;
1565 	fprintf(stderr,
1566 	    "Generating MV parameters for %d keys (%d bits)...\n", n,
1567 	    modulus2 / n);
1568 	ctx = BN_CTX_new(); u = BN_new(); v = BN_new(); w = BN_new();
1569 	b = BN_new(); b1 = BN_new();
1570 	dsa = DSA_new();
1571 	p = BN_new(); q = BN_new(); g = BN_new();
1572 	priv_key = BN_new(); pub_key = BN_new();
1573 	temp = 0;
1574 	for (j = 1; j <= n; j++) {
1575 		s1[j] = BN_new();
1576 		while (1) {
1577 			BN_generate_prime_ex(s1[j], modulus2 / n, 0,
1578 					     NULL, NULL, NULL);
1579 			for (i = 1; i < j; i++) {
1580 				if (BN_cmp(s1[i], s1[j]) == 0)
1581 					break;
1582 			}
1583 			if (i == j)
1584 				break;
1585 			temp++;
1586 		}
1587 	}
1588 	fprintf(stderr, "Birthday keys regenerated %d\n", temp);
1589 
1590 	/*
1591 	 * Compute the modulus q as the product of the primes. Compute
1592 	 * the modulus p as 2 * q + 1 and test p for primality. If p
1593 	 * is composite, replace one of the primes with a new distinct
1594 	 * one and try again. Note that q will hardly be a secret since
1595 	 * we have to reveal p to servers, but not clients. However,
1596 	 * factoring q to find the primes should be adequately hard, as
1597 	 * this is the same problem considered hard in RSA. Question: is
1598 	 * it as hard to find n small prime factors totalling n bits as
1599 	 * it is to find two large prime factors totalling n bits?
1600 	 * Remember, the bad guy doesn't know n.
1601 	 */
1602 	temp = 0;
1603 	while (1) {
1604 		BN_one(q);
1605 		for (j = 1; j <= n; j++)
1606 			BN_mul(q, q, s1[j], ctx);
1607 		BN_copy(p, q);
1608 		BN_add(p, p, p);
1609 		BN_add_word(p, 1);
1610 		if (BN_is_prime_ex(p, BN_prime_checks, ctx, NULL))
1611 			break;
1612 
1613 		temp++;
1614 		j = temp % n + 1;
1615 		while (1) {
1616 			BN_generate_prime_ex(u, modulus2 / n, 0,
1617 					     NULL, NULL, NULL);
1618 			for (i = 1; i <= n; i++) {
1619 				if (BN_cmp(u, s1[i]) == 0)
1620 					break;
1621 			}
1622 			if (i > n)
1623 				break;
1624 		}
1625 		BN_copy(s1[j], u);
1626 	}
1627 	fprintf(stderr, "Defective keys regenerated %d\n", temp);
1628 
1629 	/*
1630 	 * Compute the generator g using a random roll such that
1631 	 * gcd(g, p - 1) = 1 and g^q = 1. This is a generator of p, not
1632 	 * q. This may take several iterations.
1633 	 */
1634 	BN_copy(v, p);
1635 	BN_sub_word(v, 1);
1636 	while (1) {
1637 		BN_rand(g, BN_num_bits(p) - 1, 0, 0);
1638 		BN_mod(g, g, p, ctx);
1639 		BN_gcd(u, g, v, ctx);
1640 		if (!BN_is_one(u))
1641 			continue;
1642 
1643 		BN_mod_exp(u, g, q, p, ctx);
1644 		if (BN_is_one(u))
1645 			break;
1646 	}
1647 
1648 	DSA_set0_pqg(dsa, p, q, g);
1649 
1650 	/*
1651 	 * Setup is now complete. Roll random polynomial roots x[j]
1652 	 * (j = 1...n) for all j. While it may not be strictly
1653 	 * necessary, Make sure each root has no factors in common with
1654 	 * q.
1655 	 */
1656 	fprintf(stderr,
1657 	    "Generating polynomial coefficients for %d roots (%d bits)\n",
1658 	    n, BN_num_bits(q));
1659 	for (j = 1; j <= n; j++) {
1660 		x[j] = BN_new();
1661 
1662 		while (1) {
1663 			BN_rand(x[j], BN_num_bits(q), 0, 0);
1664 			BN_mod(x[j], x[j], q, ctx);
1665 			BN_gcd(u, x[j], q, ctx);
1666 			if (BN_is_one(u))
1667 				break;
1668 		}
1669 	}
1670 
1671 	/*
1672 	 * Generate polynomial coefficients a[i] (i = 0...n) from the
1673 	 * expansion of root products (x - x[j]) mod q for all j. The
1674 	 * method is a present from Charlie Boncelet.
1675 	 */
1676 	for (i = 0; i <= n; i++) {
1677 		a[i] = BN_new();
1678 		BN_one(a[i]);
1679 	}
1680 	for (j = 1; j <= n; j++) {
1681 		BN_zero(w);
1682 		for (i = 0; i < j; i++) {
1683 			BN_copy(u, q);
1684 			BN_mod_mul(v, a[i], x[j], q, ctx);
1685 			BN_sub(u, u, v);
1686 			BN_add(u, u, w);
1687 			BN_copy(w, a[i]);
1688 			BN_mod(a[i], u, q, ctx);
1689 		}
1690 	}
1691 
1692 	/*
1693 	 * Generate gs[i] = g^a[i] mod p for all i and the generator g.
1694 	 */
1695 	for (i = 0; i <= n; i++) {
1696 		gs[i] = BN_new();
1697 		BN_mod_exp(gs[i], g, a[i], p, ctx);
1698 	}
1699 
1700 	/*
1701 	 * Verify prod(gs[i]^(a[i] x[j]^i)) = 1 for all i, j. Note the
1702 	 * a[i] x[j]^i exponent is computed mod q, but the gs[i] is
1703 	 * computed mod p. also note the expression given in the paper
1704 	 * is incorrect.
1705 	 */
1706 	temp = 1;
1707 	for (j = 1; j <= n; j++) {
1708 		BN_one(u);
1709 		for (i = 0; i <= n; i++) {
1710 			BN_set_word(v, i);
1711 			BN_mod_exp(v, x[j], v, q, ctx);
1712 			BN_mod_mul(v, v, a[i], q, ctx);
1713 			BN_mod_exp(v, g, v, p, ctx);
1714 			BN_mod_mul(u, u, v, p, ctx);
1715 		}
1716 		if (!BN_is_one(u))
1717 			temp = 0;
1718 	}
1719 	fprintf(stderr,
1720 	    "Confirm prod(gs[i]^(x[j]^i)) = 1 for all i, j: %s\n", temp ?
1721 	    "yes" : "no");
1722 	if (!temp) {
1723 		return (NULL);
1724 	}
1725 
1726 	/*
1727 	 * Make private encryption key A. Keep it around for awhile,
1728 	 * since it is expensive to compute.
1729 	 */
1730 	biga = BN_new();
1731 
1732 	BN_one(biga);
1733 	for (j = 1; j <= n; j++) {
1734 		for (i = 0; i < n; i++) {
1735 			BN_set_word(v, i);
1736 			BN_mod_exp(v, x[j], v, q, ctx);
1737 			BN_mod_exp(v, gs[i], v, p, ctx);
1738 			BN_mod_mul(biga, biga, v, p, ctx);
1739 		}
1740 	}
1741 
1742 	/*
1743 	 * Roll private random group key b mod q (0 < b < q), where
1744 	 * gcd(b, q) = 1 to guarantee b^-1 exists, then compute b^-1
1745 	 * mod q. If b is changed, the client keys must be recomputed.
1746 	 */
1747 	while (1) {
1748 		BN_rand(b, BN_num_bits(q), 0, 0);
1749 		BN_mod(b, b, q, ctx);
1750 		BN_gcd(u, b, q, ctx);
1751 		if (BN_is_one(u))
1752 			break;
1753 	}
1754 	BN_mod_inverse(b1, b, q, ctx);
1755 
1756 	/*
1757 	 * Make private client keys (xbar[j], xhat[j]) for all j. Note
1758 	 * that the keys for the jth client do not s1[j] or the product
1759 	 * s1[j]) (j = 1...n) which is q by construction.
1760 	 *
1761 	 * Compute the factor w such that w s1[j] = s1[j] for all j. The
1762 	 * easy way to do this is to compute (q + s1[j]) / s1[j].
1763 	 * Exercise for the student: prove the remainder is always zero.
1764 	 */
1765 	for (j = 1; j <= n; j++) {
1766 		xbar[j] = BN_new(); xhat[j] = BN_new();
1767 
1768 		BN_add(w, q, s1[j]);
1769 		BN_div(w, u, w, s1[j], ctx);
1770 		BN_zero(xbar[j]);
1771 		BN_set_word(v, n);
1772 		for (i = 1; i <= n; i++) {
1773 			if (i == j)
1774 				continue;
1775 
1776 			BN_mod_exp(u, x[i], v, q, ctx);
1777 			BN_add(xbar[j], xbar[j], u);
1778 		}
1779 		BN_mod_mul(xbar[j], xbar[j], b1, q, ctx);
1780 		BN_mod_exp(xhat[j], x[j], v, q, ctx);
1781 		BN_mod_mul(xhat[j], xhat[j], w, q, ctx);
1782 	}
1783 
1784 	/*
1785 	 * We revoke client j by dividing q by s1[j]. The quotient
1786 	 * becomes the enabling key s. Note we always have to revoke
1787 	 * one key; otherwise, the plaintext and cryptotext would be
1788 	 * identical. For the present there are no provisions to revoke
1789 	 * additional keys, so we sail on with only token revocations.
1790 	 */
1791 	s = BN_new();
1792 	BN_copy(s, q);
1793 	BN_div(s, u, s, s1[n], ctx);
1794 
1795 	/*
1796 	 * For each combination of clients to be revoked, make private
1797 	 * encryption key E = A^s and partial decryption keys gbar = g^s
1798 	 * and ghat = g^(s b), all mod p. The servers use these keys to
1799 	 * compute the session encryption key and partial decryption
1800 	 * keys. These values must be regenerated if the enabling key is
1801 	 * changed.
1802 	 */
1803 	bige = BN_new(); gbar = BN_new(); ghat = BN_new();
1804 	BN_mod_exp(bige, biga, s, p, ctx);
1805 	BN_mod_exp(gbar, g, s, p, ctx);
1806 	BN_mod_mul(v, s, b, q, ctx);
1807 	BN_mod_exp(ghat, g, v, p, ctx);
1808 
1809 	/*
1810 	 * Notes: We produce the key media in three steps. The first
1811 	 * step is to generate the system parameters p, q, g, b, A and
1812 	 * the enabling keys s1[j]. Associated with each s1[j] are
1813 	 * parameters xbar[j] and xhat[j]. All of these parameters are
1814 	 * retained in a data structure protecteted by the trusted-agent
1815 	 * password. The p, xbar[j] and xhat[j] paremeters are
1816 	 * distributed to the j clients. When the client keys are to be
1817 	 * activated, the enabled keys are multipied together to form
1818 	 * the master enabling key s. This and the other parameters are
1819 	 * used to compute the server encryption key E and the partial
1820 	 * decryption keys gbar and ghat.
1821 	 *
1822 	 * In the identity exchange the client rolls random r and sends
1823 	 * it to the server. The server rolls random k, which is used
1824 	 * only once, then computes the session key E^k and partial
1825 	 * decryption keys gbar^k and ghat^k. The server sends the
1826 	 * encrypted r along with gbar^k and ghat^k to the client. The
1827 	 * client completes the decryption and verifies it matches r.
1828 	 */
1829 	/*
1830 	 * Write the MV trusted-agent parameters and keys as a DSA
1831 	 * private key encoded in PEM.
1832 	 *
1833 	 * p	modulus p
1834 	 * q	modulus q
1835 	 * g	generator g
1836 	 * priv_key A mod p
1837 	 * pub_key b mod q
1838 	 * (remaining values are not used)
1839 	 */
1840 	i = 0;
1841 	str = fheader("MVta", "mvta", groupname);
1842 	fprintf(stderr, "Generating MV trusted-authority keys\n");
1843 	BN_copy(priv_key, biga);
1844 	BN_copy(pub_key, b);
1845 	DSA_set0_key(dsa, pub_key, priv_key);
1846 	pkey = EVP_PKEY_new();
1847 	EVP_PKEY_assign_DSA(pkey, dsa);
1848 	PEM_write_PKCS8PrivateKey(str, pkey, cipher, NULL, 0, NULL,
1849 	    passwd1);
1850 	evpars[i++] = pkey;
1851 	if (debug)
1852 		DSA_print_fp(stderr, dsa, 0);
1853 
1854 	/*
1855 	 * Append the MV server parameters and keys as a DSA key encoded
1856 	 * in PEM.
1857 	 *
1858 	 * p	modulus p
1859 	 * q	modulus q (used only when generating k)
1860 	 * g	bige
1861 	 * priv_key gbar
1862 	 * pub_key ghat
1863 	 * (remaining values are not used)
1864 	 */
1865 	fprintf(stderr, "Generating MV server keys\n");
1866 	dsa2 = DSA_new();
1867 	DSA_set0_pqg(dsa2, BN_dup(p), BN_dup(q), BN_dup(bige));
1868 	DSA_set0_key(dsa2, BN_dup(ghat), BN_dup(gbar));
1869 	pkey1 = EVP_PKEY_new();
1870 	EVP_PKEY_assign_DSA(pkey1, dsa2);
1871 	PEM_write_PKCS8PrivateKey(str, pkey1, cipher, NULL, 0, NULL,
1872 	    passwd1);
1873 	evpars[i++] = pkey1;
1874 	if (debug)
1875 		DSA_print_fp(stderr, dsa2, 0);
1876 
1877 	/*
1878 	 * Append the MV client parameters for each client j as DSA keys
1879 	 * encoded in PEM.
1880 	 *
1881 	 * p	modulus p
1882 	 * priv_key xbar[j] mod q
1883 	 * pub_key xhat[j] mod q
1884 	 * (remaining values are not used)
1885 	 */
1886 	fprintf(stderr, "Generating %d MV client keys\n", n);
1887 	for (j = 1; j <= n; j++) {
1888 		sdsa = DSA_new();
1889 		DSA_set0_pqg(sdsa, BN_dup(p), BN_dup(BN_value_one()),
1890 			BN_dup(BN_value_one()));
1891 		DSA_set0_key(sdsa, BN_dup(xhat[j]), BN_dup(xbar[j]));
1892 		pkey1 = EVP_PKEY_new();
1893 		EVP_PKEY_set1_DSA(pkey1, sdsa);
1894 		PEM_write_PKCS8PrivateKey(str, pkey1, cipher, NULL, 0,
1895 		    NULL, passwd1);
1896 		evpars[i++] = pkey1;
1897 		if (debug)
1898 			DSA_print_fp(stderr, sdsa, 0);
1899 
1900 		/*
1901 		 * The product (gbar^k)^xbar[j] (ghat^k)^xhat[j] and E
1902 		 * are inverses of each other. We check that the product
1903 		 * is one for each client except the ones that have been
1904 		 * revoked.
1905 		 */
1906 		BN_mod_exp(v, gbar, xhat[j], p, ctx);
1907 		BN_mod_exp(u, ghat, xbar[j], p, ctx);
1908 		BN_mod_mul(u, u, v, p, ctx);
1909 		BN_mod_mul(u, u, bige, p, ctx);
1910 		if (!BN_is_one(u)) {
1911 			fprintf(stderr, "Revoke key %d\n", j);
1912 			continue;
1913 		}
1914 	}
1915 	evpars[i++] = NULL;
1916 	fclose(str);
1917 
1918 	/*
1919 	 * Free the countries.
1920 	 */
1921 	for (i = 0; i <= n; i++) {
1922 		BN_free(a[i]); BN_free(gs[i]);
1923 	}
1924 	for (j = 1; j <= n; j++) {
1925 		BN_free(x[j]); BN_free(xbar[j]); BN_free(xhat[j]);
1926 		BN_free(s1[j]);
1927 	}
1928 	return (pkey);
1929 }
1930 
1931 
1932 /*
1933  * Generate X509v3 certificate.
1934  *
1935  * The certificate consists of the version number, serial number,
1936  * validity interval, issuer name, subject name and public key. For a
1937  * self-signed certificate, the issuer name is the same as the subject
1938  * name and these items are signed using the subject private key. The
1939  * validity interval extends from the current time to the same time one
1940  * year hence. For NTP purposes, it is convenient to use the NTP seconds
1941  * of the current time as the serial number.
1942  */
1943 int
1944 x509	(
1945 	EVP_PKEY *pkey,		/* signing key */
1946 	const EVP_MD *md,	/* signature/digest scheme */
1947 	char	*gqpub,		/* identity extension (hex string) */
1948 	const char *exten,	/* private cert extension */
1949 	char	*name		/* subject/issuer name */
1950 	)
1951 {
1952 	X509	*cert;		/* X509 certificate */
1953 	X509_NAME *subj;	/* distinguished (common) name */
1954 	X509_EXTENSION *ex;	/* X509v3 extension */
1955 	FILE	*str;		/* file handle */
1956 	ASN1_INTEGER *serial;	/* serial number */
1957 	const char *id;		/* digest/signature scheme name */
1958 	char	pathbuf[MAXFILENAME + 1];
1959 
1960 	/*
1961 	 * Generate X509 self-signed certificate.
1962 	 *
1963 	 * Set the certificate serial to the NTP seconds for grins. Set
1964 	 * the version to 3. Set the initial validity to the current
1965 	 * time and the finalvalidity one year hence.
1966 	 */
1967  	id = OBJ_nid2sn(EVP_MD_pkey_type(md));
1968 	fprintf(stderr, "Generating new certificate %s %s\n", name, id);
1969 	cert = X509_new();
1970 	X509_set_version(cert, 2L);
1971 	serial = ASN1_INTEGER_new();
1972 	ASN1_INTEGER_set(serial, (long)epoch + JAN_1970);
1973 	X509_set_serialNumber(cert, serial);
1974 	ASN1_INTEGER_free(serial);
1975 	X509_time_adj(X509_get_notBefore(cert), 0L, &epoch);
1976 	X509_time_adj(X509_get_notAfter(cert), lifetime * SECSPERDAY, &epoch);
1977 	subj = X509_get_subject_name(cert);
1978 	X509_NAME_add_entry_by_txt(subj, "commonName", MBSTRING_ASC,
1979 	    (u_char *)name, -1, -1, 0);
1980 	subj = X509_get_issuer_name(cert);
1981 	X509_NAME_add_entry_by_txt(subj, "commonName", MBSTRING_ASC,
1982 	    (u_char *)name, -1, -1, 0);
1983 	if (!X509_set_pubkey(cert, pkey)) {
1984 		fprintf(stderr, "Assign certificate signing key fails\n%s\n",
1985 		    ERR_error_string(ERR_get_error(), NULL));
1986 		X509_free(cert);
1987 		return (0);
1988 	}
1989 
1990 	/*
1991 	 * Add X509v3 extensions if present. These represent the minimum
1992 	 * set defined in RFC3280 less the certificate_policy extension,
1993 	 * which is seriously obfuscated in OpenSSL.
1994 	 */
1995 	/*
1996 	 * The basic_constraints extension CA:TRUE allows servers to
1997 	 * sign client certficitates.
1998 	 */
1999 	fprintf(stderr, "%s: %s\n", LN_basic_constraints,
2000 	    BASIC_CONSTRAINTS);
2001 	ex = X509V3_EXT_conf_nid(NULL, NULL, NID_basic_constraints,
2002 	    _UC(BASIC_CONSTRAINTS));
2003 	if (!X509_add_ext(cert, ex, -1)) {
2004 		fprintf(stderr, "Add extension field fails\n%s\n",
2005 		    ERR_error_string(ERR_get_error(), NULL));
2006 		return (0);
2007 	}
2008 	X509_EXTENSION_free(ex);
2009 
2010 	/*
2011 	 * The key_usage extension designates the purposes the key can
2012 	 * be used for.
2013 	 */
2014 	fprintf(stderr, "%s: %s\n", LN_key_usage, KEY_USAGE);
2015 	ex = X509V3_EXT_conf_nid(NULL, NULL, NID_key_usage, _UC(KEY_USAGE));
2016 	if (!X509_add_ext(cert, ex, -1)) {
2017 		fprintf(stderr, "Add extension field fails\n%s\n",
2018 		    ERR_error_string(ERR_get_error(), NULL));
2019 		return (0);
2020 	}
2021 	X509_EXTENSION_free(ex);
2022 	/*
2023 	 * The subject_key_identifier is used for the GQ public key.
2024 	 * This should not be controversial.
2025 	 */
2026 	if (gqpub != NULL) {
2027 		fprintf(stderr, "%s\n", LN_subject_key_identifier);
2028 		ex = X509V3_EXT_conf_nid(NULL, NULL,
2029 		    NID_subject_key_identifier, gqpub);
2030 		if (!X509_add_ext(cert, ex, -1)) {
2031 			fprintf(stderr,
2032 			    "Add extension field fails\n%s\n",
2033 			    ERR_error_string(ERR_get_error(), NULL));
2034 			return (0);
2035 		}
2036 		X509_EXTENSION_free(ex);
2037 	}
2038 
2039 	/*
2040 	 * The extended key usage extension is used for special purpose
2041 	 * here. The semantics probably do not conform to the designer's
2042 	 * intent and will likely change in future.
2043 	 *
2044 	 * "trustRoot" designates a root authority
2045 	 * "private" designates a private certificate
2046 	 */
2047 	if (exten != NULL) {
2048 		fprintf(stderr, "%s: %s\n", LN_ext_key_usage, exten);
2049 		ex = X509V3_EXT_conf_nid(NULL, NULL,
2050 		    NID_ext_key_usage, _UC(exten));
2051 		if (!X509_add_ext(cert, ex, -1)) {
2052 			fprintf(stderr,
2053 			    "Add extension field fails\n%s\n",
2054 			    ERR_error_string(ERR_get_error(), NULL));
2055 			return (0);
2056 		}
2057 		X509_EXTENSION_free(ex);
2058 	}
2059 
2060 	/*
2061 	 * Sign and verify.
2062 	 */
2063 	X509_sign(cert, pkey, md);
2064 	if (X509_verify(cert, pkey) <= 0) {
2065 		fprintf(stderr, "Verify %s certificate fails\n%s\n", id,
2066 		    ERR_error_string(ERR_get_error(), NULL));
2067 		X509_free(cert);
2068 		return (0);
2069 	}
2070 
2071 	/*
2072 	 * Write the certificate encoded in PEM.
2073 	 */
2074 	snprintf(pathbuf, sizeof(pathbuf), "%scert", id);
2075 	str = fheader(pathbuf, "cert", hostname);
2076 	PEM_write_X509(str, cert);
2077 	fclose(str);
2078 	if (debug)
2079 		X509_print_fp(stderr, cert);
2080 	X509_free(cert);
2081 	return (1);
2082 }
2083 
2084 #if 0	/* asn2ntp is used only with commercial certificates */
2085 /*
2086  * asn2ntp - convert ASN1_TIME time structure to NTP time
2087  */
2088 u_long
2089 asn2ntp	(
2090 	ASN1_TIME *asn1time	/* pointer to ASN1_TIME structure */
2091 	)
2092 {
2093 	char	*v;		/* pointer to ASN1_TIME string */
2094 	struct	tm tm;		/* time decode structure time */
2095 
2096 	/*
2097 	 * Extract time string YYMMDDHHMMSSZ from ASN.1 time structure.
2098 	 * Note that the YY, MM, DD fields start with one, the HH, MM,
2099 	 * SS fiels start with zero and the Z character should be 'Z'
2100 	 * for UTC. Also note that years less than 50 map to years
2101 	 * greater than 100. Dontcha love ASN.1?
2102 	 */
2103 	if (asn1time->length > 13)
2104 		return (-1);
2105 	v = (char *)asn1time->data;
2106 	tm.tm_year = (v[0] - '0') * 10 + v[1] - '0';
2107 	if (tm.tm_year < 50)
2108 		tm.tm_year += 100;
2109 	tm.tm_mon = (v[2] - '0') * 10 + v[3] - '0' - 1;
2110 	tm.tm_mday = (v[4] - '0') * 10 + v[5] - '0';
2111 	tm.tm_hour = (v[6] - '0') * 10 + v[7] - '0';
2112 	tm.tm_min = (v[8] - '0') * 10 + v[9] - '0';
2113 	tm.tm_sec = (v[10] - '0') * 10 + v[11] - '0';
2114 	tm.tm_wday = 0;
2115 	tm.tm_yday = 0;
2116 	tm.tm_isdst = 0;
2117 	return (mktime(&tm) + JAN_1970);
2118 }
2119 #endif
2120 
2121 /*
2122  * Callback routine
2123  */
2124 void
2125 cb	(
2126 	int	n1,		/* arg 1 */
2127 	int	n2,		/* arg 2 */
2128 	void	*chr		/* arg 3 */
2129 	)
2130 {
2131 	switch (n1) {
2132 	case 0:
2133 		d0++;
2134 		fprintf(stderr, "%s %d %d %lu\r", (char *)chr, n1, n2,
2135 		    d0);
2136 		break;
2137 	case 1:
2138 		d1++;
2139 		fprintf(stderr, "%s\t\t%d %d %lu\r", (char *)chr, n1,
2140 		    n2, d1);
2141 		break;
2142 	case 2:
2143 		d2++;
2144 		fprintf(stderr, "%s\t\t\t\t%d %d %lu\r", (char *)chr,
2145 		    n1, n2, d2);
2146 		break;
2147 	case 3:
2148 		d3++;
2149 		fprintf(stderr, "%s\t\t\t\t\t\t%d %d %lu\r",
2150 		    (char *)chr, n1, n2, d3);
2151 		break;
2152 	}
2153 }
2154 
2155 
2156 /*
2157  * Generate key
2158  */
2159 EVP_PKEY *			/* public/private key pair */
2160 genkey(
2161 	const char *type,	/* key type (RSA or DSA) */
2162 	const char *id		/* file name id */
2163 	)
2164 {
2165 	if (type == NULL)
2166 		return (NULL);
2167 	if (strcmp(type, "RSA") == 0)
2168 		return (gen_rsa(id));
2169 
2170 	else if (strcmp(type, "DSA") == 0)
2171 		return (gen_dsa(id));
2172 
2173 	fprintf(stderr, "Invalid %s key type %s\n", id, type);
2174 	return (NULL);
2175 }
2176 
2177 static RSA*
2178 genRsaKeyPair(
2179 	int	bits,
2180 	char *	what
2181 	)
2182 {
2183 	RSA *		rsa = RSA_new();
2184 	BN_GENCB *	gcb = BN_GENCB_new();
2185 	BIGNUM *	bne = BN_new();
2186 
2187 	if (gcb)
2188 		BN_GENCB_set_old(gcb, cb, what);
2189 	if (bne)
2190 		BN_set_word(bne, 65537);
2191 	if (!(rsa && gcb && bne && RSA_generate_key_ex(
2192 		      rsa, bits, bne, gcb)))
2193 	{
2194 		RSA_free(rsa);
2195 		rsa = NULL;
2196 	}
2197 	BN_GENCB_free(gcb);
2198 	BN_free(bne);
2199 	return rsa;
2200 }
2201 
2202 static DSA*
2203 genDsaParams(
2204 	int	bits,
2205 	char *	what
2206 	)
2207 {
2208 
2209 	DSA *		dsa = DSA_new();
2210 	BN_GENCB *	gcb = BN_GENCB_new();
2211 	u_char		seed[20];
2212 
2213 	if (gcb)
2214 		BN_GENCB_set_old(gcb, cb, what);
2215 	RAND_bytes(seed, sizeof(seed));
2216 	if (!(dsa && gcb && DSA_generate_parameters_ex(
2217 		      dsa, bits, seed, sizeof(seed), NULL, NULL, gcb)))
2218 	{
2219 		DSA_free(dsa);
2220 		dsa = NULL;
2221 	}
2222 	BN_GENCB_free(gcb);
2223 	return dsa;
2224 }
2225 
2226 #endif	/* AUTOKEY */
2227 
2228 
2229 /*
2230  * Generate file header and link
2231  */
2232 FILE *
2233 fheader	(
2234 	const char *file,	/* file name id */
2235 	const char *ulink,	/* linkname */
2236 	const char *owner	/* owner name */
2237 	)
2238 {
2239 	FILE	*str;		/* file handle */
2240 	char	linkname[MAXFILENAME]; /* link name */
2241 	int	temp;
2242 #ifdef HAVE_UMASK
2243         mode_t  orig_umask;
2244 #endif
2245 
2246 	snprintf(filename, sizeof(filename), "ntpkey_%s_%s.%u", file,
2247 	    owner, fstamp);
2248 #ifdef HAVE_UMASK
2249         orig_umask = umask( S_IWGRP | S_IRWXO );
2250         str = fopen(filename, "w");
2251         (void) umask(orig_umask);
2252 #else
2253         str = fopen(filename, "w");
2254 #endif
2255 	if (str == NULL) {
2256 		perror("Write");
2257 		exit (-1);
2258 	}
2259         if (strcmp(ulink, "md5") == 0) {
2260           strcpy(linkname,"ntp.keys");
2261         } else {
2262           snprintf(linkname, sizeof(linkname), "ntpkey_%s_%s", ulink,
2263                    hostname);
2264         }
2265 	(void)remove(linkname);		/* The symlink() line below matters */
2266 	temp = symlink(filename, linkname);
2267 	if (temp < 0)
2268 		perror(file);
2269 	fprintf(stderr, "Generating new %s file and link\n", ulink);
2270 	fprintf(stderr, "%s->%s\n", linkname, filename);
2271 	fprintf(str, "# %s\n# %s\n", filename, ctime(&epoch));
2272 	return (str);
2273 }
2274