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