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