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