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