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