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