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