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