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