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