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