2 * Program to generate cryptographic keys for ntp clients and servers
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.
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.
17 * ntpkey_MD5key_<hostname>.<filestamp>
18 * MD5 (128-bit) keys used to compute message digests in symmetric
21 * ntpkey_RSAhost_<hostname>.<filestamp>
22 * ntpkey_host_<hostname>
23 * RSA private/public host key pair used for public key signatures
25 * ntpkey_RSAsign_<hostname>.<filestamp>
26 * ntpkey_sign_<hostname>
27 * RSA private/public sign key pair used for public key signatures
29 * ntpkey_DSAsign_<hostname>.<filestamp>
30 * ntpkey_sign_<hostname>
31 * DSA Private/public sign key pair used for public key signatures
33 * Available digest/signature schemes
35 * RSA: RSA-MD2, RSA-MD5, RSA-SHA, RSA-SHA1, RSA-MDC2, EVP-RIPEMD160
36 * DSA: DSA-SHA, DSA-SHA1
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
44 * Identity schemes. The key type par is used for the challenge; the key
45 * type key is used for the response.
47 * ntpkey_IFFkey_<groupname>.<filestamp>
48 * ntpkey_iffkey_<groupname>
49 * Schnorr (IFF) identity parameters and keys
51 * ntpkey_GQkey_<groupname>.<filestamp>,
52 * ntpkey_gqkey_<groupname>
53 * Guillou-Quisquater (GQ) identity parameters and keys
55 * ntpkey_MVkeyX_<groupname>.<filestamp>,
56 * ntpkey_mvkey_<groupname>
57 * Mu-Varadharajan (MV) identity parameters and keys
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
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.
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.
90 #include <sys/types.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"
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"
110 #include <ssl_applink.c>
112 #define _UC(str) ((char *)(intptr_t)(str))
116 #define MD5KEYS 10 /* number of keys generated of each type */
117 #define MD5SIZE 20 /* maximum key size */
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 */
124 * Strings used in X509v3 extension fields
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"
135 FILE *fheader (const char *, const char *, const char *);
136 int gen_md5 (const char *);
137 void followlink (char *, size_t);
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 *,
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 *);
153 static DSA* genDsaParams(int, char*);
154 static RSA* genRsaKeyPair(int, char*);
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 */
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;
183 BOOL init_randfile();
186 * Don't try to follow symbolic links on Windows. Assume link == file.
195 return (int)strlen(file); /* assume no overflow possible */
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().
212 typedef BOOL (WINAPI *PCREATEHARDLINKA)(
213 __in LPCSTR lpFileName,
214 __in LPCSTR lpExistingFileName,
215 __reserved LPSECURITY_ATTRIBUTES lpSA
217 static PCREATEHARDLINKA pCreateHardLinkA;
226 hDll = LoadLibrary("kernel32");
227 pfn = GetProcAddress(hDll, "CreateHardLinkA");
228 pCreateHardLinkA = (PCREATEHARDLINKA)pfn;
231 if (NULL == pCreateHardLinkA) {
236 link_created = (*pCreateHardLinkA)(linkname, filename, NULL);
241 saved_errno = GetLastError(); /* yes we play loose */
242 mfprintf(stderr, "Create hard link %s to %s failed: %m\n",
250 WORD wVersionRequested;
252 wVersionRequested = MAKEWORD(2,0);
253 if (WSAStartup(wVersionRequested, &wsaData))
255 fprintf(stderr, "No useable winsock.dll\n");
259 #endif /* SYS_WINNT */
263 * followlink() - replace filename with its target if symlink.
265 * Some readlink() implementations do not null-terminate the result.
277 len = readlink(fname, fname, (int)bufsiz);
282 if (len > (int)bufsiz - 1)
283 len = (int)bufsiz - 1;
293 int argc, /* command line options */
297 struct timeval tv; /* initialization vector */
298 int md5key = 0; /* generate MD5 keys */
299 int optct; /* option count */
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];
333 /* Initialize before OpenSSL checks */
335 if (!init_randfile())
336 fprintf(stderr, "Unable to initialize .rnd file\n");
344 ntp_crypto_srandom();
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.
351 gethostname(hostbuf, sizeof(hostbuf) - 1);
352 hostbuf[COUNTOF(hostbuf) - 1] = '\0';
357 GETTIMEOFDAY(&tv, NULL);
359 fstamp = (u_int)(epoch + JAN_1970);
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.
366 if (SSLeay() == SSLEAY_VERSION_NUMBER)
367 fprintf(stderr, "Using OpenSSL version %s\n",
368 SSLeay_version(SSLEAY_VERSION));
370 fprintf(stderr, "Built against OpenSSL %s, using version %s\n",
371 OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
374 debug = OPT_VALUE_SET_DEBUG_LEVEL;
376 if (HAVE_OPT( MD5KEY ))
379 if (HAVE_OPT( PASSWORD ))
380 passwd1 = estrdup(OPT_ARG( PASSWORD ));
382 if (HAVE_OPT( EXPORT_PASSWD ))
383 passwd2 = estrdup(OPT_ARG( EXPORT_PASSWD ));
385 if (HAVE_OPT( HOST_KEY ))
388 if (HAVE_OPT( SIGN_KEY ))
389 sign = estrdup(OPT_ARG( SIGN_KEY ));
391 if (HAVE_OPT( GQ_PARAMS ))
394 if (HAVE_OPT( IFFKEY ))
397 if (HAVE_OPT( MV_PARAMS )) {
399 nkeys = OPT_VALUE_MV_PARAMS;
401 if (HAVE_OPT( MV_KEYS )) {
403 nkeys = OPT_VALUE_MV_KEYS;
406 if (HAVE_OPT( IMBITS ))
407 modulus2 = OPT_VALUE_IMBITS;
409 if (HAVE_OPT( MODULUS ))
410 modulus = OPT_VALUE_MODULUS;
412 if (HAVE_OPT( CERTIFICATE ))
413 scheme = OPT_ARG( CERTIFICATE );
415 if (HAVE_OPT( CIPHER ))
416 ciphername = OPT_ARG( CIPHER );
418 if (HAVE_OPT( SUBJECT_NAME ))
419 hostname = estrdup(OPT_ARG( SUBJECT_NAME ));
421 if (HAVE_OPT( IDENT ))
422 groupname = estrdup(OPT_ARG( IDENT ));
424 if (HAVE_OPT( LIFETIME ))
425 lifetime = OPT_VALUE_LIFETIME;
427 if (HAVE_OPT( PVT_CERT ))
428 exten = EXT_KEY_PRIVATE;
430 if (HAVE_OPT( TRUSTED_CERT ))
431 exten = EXT_KEY_TRUST;
434 * Remove the group name from the hostname variable used
435 * in host and sign certificate file names.
437 if (hostname != hostbuf)
438 ptr = strchr(hostname, '@');
443 groupname = estrdup(ptr + 1);
444 /* -s @group is equivalent to -i group, host unch. */
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.
456 if (groupname == hostbuf) {
459 snprintf(certnamebuf, sizeof(certnamebuf), "%s@%s",
460 hostname, groupname);
461 certname = certnamebuf;
465 * Seed random number generator and grow weeds.
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));
475 temp = RAND_load_file(pathbuf, -1);
478 "RAND_load_file %s not found or empty\n",
483 "Random seed file %s %u bytes\n", pathbuf, temp);
484 RAND_add(&epoch, sizeof(epoch), 4.0);
489 * Create new unencrypted MD5 keys file if requested. If this
490 * option is selected, ignore all other options.
499 * Load previous certificate if available.
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);
509 * Extract subject name.
511 X509_NAME_oneline(X509_get_subject_name(cert), groupbuf,
515 * Extract digest/signature scheme.
517 if (scheme == NULL) {
518 nid = X509_get_signature_nid(cert);
519 scheme = OBJ_nid2sn(nid);
523 * If a key_usage extension field is present, determine
524 * whether this is a trusted or private certificate.
527 ptr = strstr(groupbuf, "CN=");
528 cnt = X509_get_ext_count(cert);
529 for (i = 0; i < cnt; i++) {
533 ext = X509_get_ext(cert, i);
534 obj = X509_EXTENSION_get_object(ext);
536 if (OBJ_obj2nid(obj) ==
538 bp = BIO_new(BIO_s_mem());
539 X509V3_EXT_print(bp, ext, 0, 0);
540 BIO_gets(bp, pathbuf,
545 exten = EXT_KEY_TRUST;
546 else if (strcmp(pathbuf,
548 exten = EXT_KEY_PRIVATE;
549 certname = estrdup(ptr + 3);
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);
563 fprintf(stderr, "Using host %s group %s\n", hostname,
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
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",
582 pkey_host = genkey("RSA", "host");
585 if (pkey_host == NULL) {
586 fprintf(stderr, "Generating host key fails\n");
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.
596 pkey_sign = genkey(sign, "sign");
597 if (pkey_sign == NULL) {
598 snprintf(filename, sizeof(filename), "ntpkey_sign_%s",
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",
606 pkey_sign = pkey_host;
607 fprintf(stderr, "Using host key as sign key\n");
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.
617 pkey_gqkey = gen_gqkey("gqkey");
618 if (pkey_gqkey == NULL) {
619 snprintf(filename, sizeof(filename), "ntpkey_gqkey_%s",
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",
628 if (pkey_gqkey != NULL) {
632 rsa = EVP_PKEY_get0_RSA(pkey_gqkey);
633 RSA_get0_factors(rsa, NULL, &q);
634 grpkey = BN_bn2hex(q);
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.
642 if (pkey_gqkey != NULL && HAVE_OPT(ID_KEY)) {
645 snprintf(filename, sizeof(filename),
646 "ntpkey_gqpar_%s.%u", groupname, fstamp);
647 fprintf(stderr, "Writing GQ parameters %s to stdout\n",
649 fprintf(stdout, "# %s\n# %s\n", filename,
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,
661 RSA_print_fp(stderr, rsa, 0);
665 * Write the encrypted GQ server keys to the stdout stream.
667 if (pkey_gqkey != NULL && passwd2 != NULL) {
670 snprintf(filename, sizeof(filename),
671 "ntpkey_gqkey_%s.%u", groupname, fstamp);
672 fprintf(stderr, "Writing GQ keys %s to stdout\n",
674 fprintf(stdout, "# %s\n# %s\n", filename,
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,
683 RSA_print_fp(stderr, rsa, 0);
687 * Create new encrypted IFF server keys file if requested;
688 * otherwise, look for existing file.
691 pkey_iffkey = gen_iffkey("iffkey");
692 if (pkey_iffkey == NULL) {
693 snprintf(filename, sizeof(filename), "ntpkey_iffkey_%s",
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",
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.
708 if (pkey_iffkey != NULL && HAVE_OPT(ID_KEY)) {
711 snprintf(filename, sizeof(filename),
712 "ntpkey_iffpar_%s.%u", groupname, fstamp);
713 fprintf(stderr, "Writing IFF parameters %s to stdout\n",
715 fprintf(stdout, "# %s\n# %s\n", filename,
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,
727 DSA_print_fp(stderr, dsa, 0);
731 * Write the encrypted IFF server keys to the stdout stream.
733 if (pkey_iffkey != NULL && passwd2 != NULL) {
736 snprintf(filename, sizeof(filename),
737 "ntpkey_iffkey_%s.%u", groupname, fstamp);
738 fprintf(stderr, "Writing IFF keys %s to stdout\n",
740 fprintf(stdout, "# %s\n# %s\n", filename,
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,
749 DSA_print_fp(stderr, dsa, 0);
753 * Create new encrypted MV trusted-authority keys file if
754 * requested; otherwise, look for existing keys file.
757 pkey_mvkey = gen_mvkey("mv", pkey_mvpar);
758 if (pkey_mvkey == NULL) {
759 snprintf(filename, sizeof(filename), "ntpkey_mvta_%s",
761 pkey_mvkey = readkey(filename, passwd1, &fstamp,
763 if (pkey_mvkey != NULL) {
764 followlink(filename, sizeof(filename));
765 fprintf(stderr, "Using MV keys %s\n",
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.
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",
780 fprintf(stdout, "# %s\n# %s\n", filename,
782 pkey = pkey_mvpar[2];
783 PEM_write_PKCS8PrivateKey(stdout, pkey, NULL, NULL, 0,
787 DSA_print_fp(stderr, EVP_PKEY_get0_DSA(pkey), 0);
791 * Write the encrypted MV server keys to the stdout stream.
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",
798 fprintf(stdout, "# %s\n# %s\n", filename,
800 pkey = pkey_mvpar[1];
801 PEM_write_PKCS8PrivateKey(stdout, pkey, cipher, NULL, 0,
805 DSA_print_fp(stderr, EVP_PKEY_get0_DSA(pkey), 0);
809 * Decode the digest/signature scheme and create the
810 * certificate. Do this every time we run the program.
812 ectx = EVP_get_digestbyname(scheme);
815 "Invalid digest/signature combination %s\n",
819 x509(pkey_sign, ectx, grpkey, exten, certname);
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.
832 const char *id /* file name id */
835 u_char md5key[MD5SIZE + 1]; /* MD5 key */
839 u_char keystr[MD5SIZE];
840 u_char hexstr[2 * MD5SIZE + 1];
841 u_char hex[] = "0123456789abcdef";
844 str = fheader("MD5key", id, groupname);
845 for (i = 1; i <= MD5KEYS; i++) {
846 for (j = 0; j < MD5SIZE; j++) {
852 rc = ntp_crypto_random_buf(
853 &temp, sizeof(temp));
855 fprintf(stderr, "ntp_crypto_random_buf() failed.\n");
861 if (temp > 0x20 && temp < 0x7f)
867 fprintf(str, "%2d MD5 %s # MD5 key\n", i,
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];
877 hexstr[2 * MD5SIZE] = '\0';
878 fprintf(str, "%2d SHA1 %s # SHA1 key\n", i + MD5KEYS,
889 * readkey - load cryptographic parameters and keys
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.
895 EVP_PKEY * /* public/private key pair */
897 char *cp, /* file name */
898 char *passwd, /* password */
899 u_int *estamp, /* file stamp */
900 EVP_PKEY **evpars /* parameter list pointer */
903 FILE *str; /* file handle */
904 EVP_PKEY *pkey = NULL; /* public/private key */
905 u_int gstamp; /* filestamp */
906 char linkname[MAXFILENAME]; /* filestamp buffer) */
914 str = fopen(cp, "r");
919 * Read the filestamp, which is contained in the first line.
921 if ((ptr = fgets(linkname, MAXFILENAME, str)) == NULL) {
922 fprintf(stderr, "Empty key file %s\n", cp);
926 if ((ptr = strrchr(ptr, '.')) == NULL) {
927 fprintf(stderr, "No filestamp found in %s\n", cp);
931 if (sscanf(++ptr, "%u", &gstamp) != 1) {
932 fprintf(stderr, "Invalid filestamp found in %s\n", cp);
938 * Read and decrypt PEM-encoded private keys. The first one
939 * found is returned. If others are expected, add them to the
942 for (i = 0; i <= MVMAX - 1;) {
943 parkey = PEM_read_PrivateKey(str, NULL, NULL, passwd);
944 if (evpars != NULL) {
945 evpars[i++] = parkey;
954 if (EVP_PKEY_base_id(parkey) == EVP_PKEY_DSA)
955 DSA_print_fp(stderr, EVP_PKEY_get0_DSA(parkey),
957 else if (EVP_PKEY_base_id(parkey) == EVP_PKEY_RSA)
958 RSA_print_fp(stderr, EVP_PKEY_get0_RSA(parkey),
964 fprintf(stderr, "Corrupt file %s or wrong key %s\n%s\n",
965 cp, passwd, ERR_error_string(ERR_get_error(),
975 * Generate RSA public/private key pair
977 EVP_PKEY * /* public/private key pair */
979 const char *id /* file name id */
982 EVP_PKEY *pkey; /* private key */
983 RSA *rsa; /* RSA parameters and key pair */
986 fprintf(stderr, "Generating RSA keys (%d bits)...\n", modulus);
987 rsa = genRsaKeyPair(modulus, _UC("RSA"));
988 fprintf(stderr, "\n");
990 fprintf(stderr, "RSA generate keys fails\n%s\n",
991 ERR_error_string(ERR_get_error(), NULL));
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
1001 if (!RSA_check_key(rsa)) {
1002 fprintf(stderr, "Invalid RSA key\n%s\n",
1003 ERR_error_string(ERR_get_error(), NULL));
1009 * Write the RSA parameters and keys as a RSA private key
1012 if (strcmp(id, "sign") == 0)
1013 str = fheader("RSAsign", id, hostname);
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,
1022 RSA_print_fp(stderr, rsa, 0);
1028 * Generate DSA public/private key pair
1030 EVP_PKEY * /* public/private key pair */
1032 const char *id /* file name id */
1035 EVP_PKEY *pkey; /* private key */
1036 DSA *dsa; /* DSA parameters */
1040 * Generate DSA parameters.
1043 "Generating DSA parameters (%d bits)...\n", modulus);
1044 dsa = genDsaParams(modulus, _UC("DSA"));
1045 fprintf(stderr, "\n");
1047 fprintf(stderr, "DSA generate parameters fails\n%s\n",
1048 ERR_error_string(ERR_get_error(), NULL));
1053 * Generate DSA keys.
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));
1064 * Write the DSA parameters and keys as a DSA private key
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,
1074 DSA_print_fp(stderr, dsa, 0);
1080 ***********************************************************************
1082 * The following routines implement the Schnorr (IFF) identity scheme *
1084 ***********************************************************************
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
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
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
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.
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.
1127 * Generate Schnorr (IFF) keys.
1129 EVP_PKEY * /* DSA cuckoo nest */
1131 const char *id /* file name id */
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 */
1140 const BIGNUM *p, *q, *g;
1141 BIGNUM *pub_key, *priv_key;
1144 * Generate DSA parameters for use as IFF parameters.
1146 fprintf(stderr, "Generating IFF keys (%d bits)...\n",
1148 dsa = genDsaParams(modulus2, _UC("IFF"));
1149 fprintf(stderr, "\n");
1151 fprintf(stderr, "DSA generate parameters fails\n%s\n",
1152 ERR_error_string(ERR_get_error(), NULL));
1155 DSA_get0_pqg(dsa, &p, &q, &g);
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.
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);
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);
1172 "Confirm g^(q - b) g^b = 1 mod p: %s\n", temp == 1 ?
1175 BN_free(b); BN_free(r); BN_free(k);
1176 BN_free(u); BN_free(v); BN_free(w); BN_CTX_free(ctx);
1179 pub_key = BN_dup(v);
1180 priv_key = BN_dup(b);
1181 DSA_set0_key(dsa, pub_key, priv_key);
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.
1188 BN_rand(r, BN_num_bits(q), -1, 0); /* r */
1189 BN_mod(r, r, q, ctx);
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.
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 */
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 */
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
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);
1214 "Confirm g^k = g^(k + b r) g^(q - b) r: %s\n", temp ==
1216 BN_free(b); BN_free(r); BN_free(k);
1217 BN_free(u); BN_free(v); BN_free(w); BN_CTX_free(ctx);
1224 * Write the IFF keys as an encrypted DSA private key encoded in
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,
1242 DSA_print_fp(stderr, dsa, 0);
1248 ***********************************************************************
1250 * The following routines implement the Guillou-Quisquater (GQ) *
1253 ***********************************************************************
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.
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.
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
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.
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.
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.
1306 * Generate Guillou-Quisquater (GQ) parameters file.
1308 EVP_PKEY * /* RSA cuckoo nest */
1310 const char *id /* file name id */
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 */
1323 * Generate RSA parameters for use as GQ parameters.
1326 "Generating GQ parameters (%d bits)...\n",
1328 rsa = genRsaKeyPair(modulus2, _UC("GQ"));
1329 fprintf(stderr, "\n");
1331 fprintf(stderr, "RSA generate keys fails\n%s\n",
1332 ERR_error_string(ERR_get_error(), NULL));
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();
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.
1346 BN_rand(b, BN_num_bits(n), -1, 0); /* b */
1347 BN_mod(b, b, n, ctx);
1350 * When generating his certificate, Bob rolls random private key
1351 * u, then computes inverse v = u^-1.
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);
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 =
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);
1368 "Confirm u^b (u^-1)^b = 1 mod n: %s\n", temp ? "yes" :
1371 BN_free(u); BN_free(v);
1372 BN_free(g); BN_free(k); BN_free(r); BN_free(y);
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!
1381 RSA_set0_factors(rsa, BN_dup(u), BN_dup(v));
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
1388 BN_rand(r, BN_num_bits(n), -1, 0); /* r */
1389 BN_mod(r, r, n, ctx);
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.
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 */
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
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 ?
1415 BN_CTX_free(ctx); BN_free(u); BN_free(v);
1416 BN_free(g); BN_free(k); BN_free(r); BN_free(y);
1423 * Write the GQ parameter file as an encrypted RSA private key
1430 * q public key (u^-1)^b
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,
1445 RSA_print_fp(stderr, rsa, 0);
1451 ***********************************************************************
1453 * The following routines implement the Mu-Varadharajan (MV) identity *
1456 ***********************************************************************
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.
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.
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.
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.
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.
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.
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).
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.
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.
1523 EVP_PKEY * /* DSA cuckoo nest */
1525 const char *id, /* file name id */
1526 EVP_PKEY **evpars /* parameter list pointer */
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;
1550 * Generate MV parameters.
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.
1564 "Generating MV parameters for %d keys (%d bits)...\n", n,
1566 ctx = BN_CTX_new(); u = BN_new(); v = BN_new(); w = BN_new();
1567 b = BN_new(); b1 = BN_new();
1569 p = BN_new(); q = BN_new(); g = BN_new();
1570 priv_key = BN_new(); pub_key = BN_new();
1572 for (j = 1; j <= n; j++) {
1575 BN_generate_prime_ex(s1[j], modulus2 / n, 0,
1577 for (i = 1; i < j; i++) {
1578 if (BN_cmp(s1[i], s1[j]) == 0)
1586 fprintf(stderr, "Birthday keys regenerated %d\n", temp);
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.
1603 for (j = 1; j <= n; j++)
1604 BN_mul(q, q, s1[j], ctx);
1608 if (BN_is_prime_ex(p, BN_prime_checks, ctx, NULL))
1614 BN_generate_prime_ex(u, modulus2 / n, 0,
1616 for (i = 1; i <= n; i++) {
1617 if (BN_cmp(u, s1[i]) == 0)
1625 fprintf(stderr, "Defective keys regenerated %d\n", temp);
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.
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);
1641 BN_mod_exp(u, g, q, p, ctx);
1646 DSA_set0_pqg(dsa, p, q, g);
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
1655 "Generating polynomial coefficients for %d roots (%d bits)\n",
1657 for (j = 1; j <= n; j++) {
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);
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.
1674 for (i = 0; i <= n; i++) {
1678 for (j = 1; j <= n; j++) {
1680 for (i = 0; i < j; i++) {
1682 BN_mod_mul(v, a[i], x[j], q, ctx);
1686 BN_mod(a[i], u, q, ctx);
1691 * Generate gs[i] = g^a[i] mod p for all i and the generator g.
1693 for (i = 0; i <= n; i++) {
1695 BN_mod_exp(gs[i], g, a[i], p, ctx);
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
1705 for (j = 1; j <= n; j++) {
1707 for (i = 0; i <= n; 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);
1718 "Confirm prod(gs[i]^(x[j]^i)) = 1 for all i, j: %s\n", temp ?
1725 * Make private encryption key A. Keep it around for awhile,
1726 * since it is expensive to compute.
1731 for (j = 1; j <= n; j++) {
1732 for (i = 0; i < n; 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);
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.
1746 BN_rand(b, BN_num_bits(q), 0, 0);
1747 BN_mod(b, b, q, ctx);
1748 BN_gcd(u, b, q, ctx);
1752 BN_mod_inverse(b1, b, q, ctx);
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.
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.
1763 for (j = 1; j <= n; j++) {
1764 xbar[j] = BN_new(); xhat[j] = BN_new();
1766 BN_add(w, q, s1[j]);
1767 BN_div(w, u, w, s1[j], ctx);
1770 for (i = 1; i <= n; i++) {
1774 BN_mod_exp(u, x[i], v, q, ctx);
1775 BN_add(xbar[j], xbar[j], u);
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);
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.
1791 BN_div(s, u, s, s1[n], ctx);
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
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);
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.
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.
1828 * Write the MV trusted-agent parameters and keys as a DSA
1829 * private key encoded in PEM.
1836 * (remaining values are not used)
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,
1850 DSA_print_fp(stderr, dsa, 0);
1853 * Append the MV server parameters and keys as a DSA key encoded
1857 * q modulus q (used only when generating k)
1861 * (remaining values are not used)
1863 fprintf(stderr, "Generating MV server keys\n");
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,
1871 evpars[i++] = pkey1;
1873 DSA_print_fp(stderr, dsa2, 0);
1876 * Append the MV client parameters for each client j as DSA keys
1880 * priv_key xbar[j] mod q
1881 * pub_key xhat[j] mod q
1882 * (remaining values are not used)
1884 fprintf(stderr, "Generating %d MV client keys\n", n);
1885 for (j = 1; j <= n; j++) {
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,
1894 evpars[i++] = pkey1;
1896 DSA_print_fp(stderr, sdsa, 0);
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
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);
1917 * Free the countries.
1919 for (i = 0; i <= n; i++) {
1920 BN_free(a[i]); BN_free(gs[i]);
1922 for (j = 1; j <= n; j++) {
1923 BN_free(x[j]); BN_free(xbar[j]); BN_free(xhat[j]);
1931 * Generate X509v3 certificate.
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.
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 */
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];
1959 * Generate X509 self-signed certificate.
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.
1965 id = OBJ_nid2sn(EVP_MD_pkey_type(md));
1966 fprintf(stderr, "Generating new certificate %s %s\n", name, id);
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));
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.
1994 * The basic_constraints extension CA:TRUE allows servers to
1995 * sign client certficitates.
1997 fprintf(stderr, "%s: %s\n", LN_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));
2006 X509_EXTENSION_free(ex);
2009 * The key_usage extension designates the purposes the key can
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));
2019 X509_EXTENSION_free(ex);
2021 * The subject_key_identifier is used for the GQ public key.
2022 * This should not be controversial.
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)) {
2030 "Add extension field fails\n%s\n",
2031 ERR_error_string(ERR_get_error(), NULL));
2034 X509_EXTENSION_free(ex);
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.
2042 * "trustRoot" designates a root authority
2043 * "private" designates a private certificate
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)) {
2051 "Add extension field fails\n%s\n",
2052 ERR_error_string(ERR_get_error(), NULL));
2055 X509_EXTENSION_free(ex);
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));
2070 * Write the certificate encoded in PEM.
2072 snprintf(pathbuf, sizeof(pathbuf), "%scert", id);
2073 str = fheader(pathbuf, "cert", hostname);
2074 PEM_write_X509(str, cert);
2077 X509_print_fp(stderr, cert);
2082 #if 0 /* asn2ntp is used only with commercial certificates */
2084 * asn2ntp - convert ASN1_TIME time structure to NTP time
2088 ASN1_TIME *asn1time /* pointer to ASN1_TIME structure */
2091 char *v; /* pointer to ASN1_TIME string */
2092 struct tm tm; /* time decode structure time */
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?
2101 if (asn1time->length > 13)
2103 v = (char *)asn1time->data;
2104 tm.tm_year = (v[0] - '0') * 10 + v[1] - '0';
2105 if (tm.tm_year < 50)
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';
2115 return (mktime(&tm) + JAN_1970);
2126 void *chr /* arg 3 */
2132 fprintf(stderr, "%s %d %d %lu\r", (char *)chr, n1, n2,
2137 fprintf(stderr, "%s\t\t%d %d %lu\r", (char *)chr, n1,
2142 fprintf(stderr, "%s\t\t\t\t%d %d %lu\r", (char *)chr,
2147 fprintf(stderr, "%s\t\t\t\t\t\t%d %d %lu\r",
2148 (char *)chr, n1, n2, d3);
2157 EVP_PKEY * /* public/private key pair */
2159 const char *type, /* key type (RSA or DSA) */
2160 const char *id /* file name id */
2165 if (strcmp(type, "RSA") == 0)
2166 return (gen_rsa(id));
2168 else if (strcmp(type, "DSA") == 0)
2169 return (gen_dsa(id));
2171 fprintf(stderr, "Invalid %s key type %s\n", id, type);
2181 RSA * rsa = RSA_new();
2182 BN_GENCB * gcb = BN_GENCB_new();
2183 BIGNUM * bne = BN_new();
2186 BN_GENCB_set_old(gcb, cb, what);
2188 BN_set_word(bne, 65537);
2189 if (!(rsa && gcb && bne && RSA_generate_key_ex(
2190 rsa, bits, bne, gcb)))
2207 DSA * dsa = DSA_new();
2208 BN_GENCB * gcb = BN_GENCB_new();
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)))
2224 #endif /* AUTOKEY */
2228 * Generate file header and link
2232 const char *file, /* file name id */
2233 const char *ulink, /* linkname */
2234 const char *owner /* owner name */
2237 FILE *str; /* file handle */
2238 char linkname[MAXFILENAME]; /* link name */
2244 snprintf(filename, sizeof(filename), "ntpkey_%s_%s.%u", file,
2247 orig_umask = umask( S_IWGRP | S_IRWXO );
2248 str = fopen(filename, "w");
2249 (void) umask(orig_umask);
2251 str = fopen(filename, "w");
2257 if (strcmp(ulink, "md5") == 0) {
2258 strcpy(linkname,"ntp.keys");
2260 snprintf(linkname, sizeof(linkname), "ntpkey_%s_%s", ulink,
2263 (void)remove(linkname); /* The symlink() line below matters */
2264 temp = symlink(filename, linkname);
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));