#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include "ntp.h"
#include "ntp_random.h"
#include "ntp_stdlib.h"
#include "ntp_assert.h"
#include "ntp_libopts.h"
#include "ntp_unixtime.h"
#include "ntp-keygen-opts.h"
#ifdef OPENSSL
#include "openssl/bn.h"
#include "openssl/evp.h"
#include "openssl/err.h"
#include "openssl/rand.h"
#include "openssl/pem.h"
#include "openssl/x509v3.h"
#include <openssl/objects.h>
#endif
#include <ssl_applink.c>
#define _UC(str) ((char *)(intptr_t)(str))
#define MD5KEYS 10
#define MD5SIZE 20
#ifdef AUTOKEY
#define PLEN 512
#define ILEN 256
#define MVMAX 100
#define KEY_USAGE "digitalSignature,keyCertSign"
#define BASIC_CONSTRAINTS "critical,CA:TRUE"
#define EXT_KEY_PRIVATE "private"
#define EXT_KEY_TRUST "trustRoot"
#endif
extern int debug;
FILE *fheader (const char *, const char *, const char *);
int gen_md5 (const char *);
void followlink (char *, size_t);
#ifdef AUTOKEY
EVP_PKEY *gen_rsa (const char *);
EVP_PKEY *gen_dsa (const char *);
EVP_PKEY *gen_iffkey (const char *);
EVP_PKEY *gen_gqkey (const char *);
EVP_PKEY *gen_mvkey (const char *, EVP_PKEY **);
void gen_mvserv (char *, EVP_PKEY **);
int x509 (EVP_PKEY *, const EVP_MD *, char *, const char *,
char *);
void cb (int, int, void *);
EVP_PKEY *genkey (const char *, const char *);
EVP_PKEY *readkey (char *, char *, u_int *, EVP_PKEY **);
void writekey (char *, char *, u_int *, EVP_PKEY **);
u_long asn2ntp (ASN1_TIME *);
#endif
extern char *optarg;
char const *progname;
u_int lifetime = DAYSPERYEAR;
int nkeys;
time_t epoch;
u_int fstamp;
char hostbuf[MAXHOSTNAME + 1];
char *hostname = NULL;
char *groupname = NULL;
char certnamebuf[2 * sizeof(hostbuf)];
char *certname = NULL;
char *passwd1 = NULL;
char *passwd2 = NULL;
char filename[MAXFILENAME + 1];
#ifdef AUTOKEY
u_int modulus = PLEN;
u_int modulus2 = ILEN;
long d0, d1, d2, d3;
const EVP_CIPHER * cipher = NULL;
#endif
#ifdef SYS_WINNT
BOOL init_randfile();
int
readlink(
char * link,
char * file,
int len
)
{
return (int)strlen(file);
}
int
symlink(
char * filename,
char* linkname
)
{
typedef BOOL (WINAPI *PCREATEHARDLINKA)(
__in LPCSTR lpFileName,
__in LPCSTR lpExistingFileName,
__reserved LPSECURITY_ATTRIBUTES lpSA
);
static PCREATEHARDLINKA pCreateHardLinkA;
static int tried;
HMODULE hDll;
FARPROC pfn;
int link_created;
int saved_errno;
if (!tried) {
tried = TRUE;
hDll = LoadLibrary("kernel32");
pfn = GetProcAddress(hDll, "CreateHardLinkA");
pCreateHardLinkA = (PCREATEHARDLINKA)pfn;
}
if (NULL == pCreateHardLinkA) {
errno = ENOSYS;
return -1;
}
link_created = (*pCreateHardLinkA)(linkname, filename, NULL);
if (link_created)
return 0;
saved_errno = GetLastError();
mfprintf(stderr, "Create hard link %s to %s failed: %m\n",
linkname, filename);
errno = saved_errno;
return -1;
}
void
InitWin32Sockets() {
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(2,0);
if (WSAStartup(wVersionRequested, &wsaData))
{
fprintf(stderr, "No useable winsock.dll\n");
exit(1);
}
}
#endif
void
followlink(
char * fname,
size_t bufsiz
)
{
int len;
REQUIRE(bufsiz > 0);
len = readlink(fname, fname, (int)bufsiz);
if (len < 0 ) {
fname[0] = '\0';
return;
}
if (len > (int)bufsiz - 1)
len = (int)bufsiz - 1;
fname[len] = '\0';
}
int
main(
int argc,
char **argv
)
{
struct timeval tv;
int md5key = 0;
int optct;
#ifdef AUTOKEY
X509 *cert = NULL;
X509_EXTENSION *ext;
EVP_PKEY *pkey_host = NULL;
EVP_PKEY *pkey_sign = NULL;
EVP_PKEY *pkey_iffkey = NULL;
EVP_PKEY *pkey_gqkey = NULL;
EVP_PKEY *pkey_mvkey = NULL;
EVP_PKEY *pkey_mvpar[MVMAX];
int hostkey = 0;
int iffkey = 0;
int gqkey = 0;
int mvkey = 0;
int mvpar = 0;
char *sign = NULL;
EVP_PKEY *pkey = NULL;
const EVP_MD *ectx;
char pathbuf[MAXFILENAME + 1];
const char *scheme = NULL;
const char *ciphername = NULL;
const char *exten = NULL;
char *grpkey = NULL;
int nid;
FILE *fstr = NULL;
char groupbuf[MAXHOSTNAME + 1];
u_int temp;
BIO * bp;
int i, cnt;
char * ptr;
#endif
progname = argv[0];
#ifdef SYS_WINNT
InitWin32Sockets();
if (!init_randfile())
fprintf(stderr, "Unable to initialize .rnd file\n");
ssl_applink();
#endif
#ifdef OPENSSL
ssl_check_version();
#endif
ntp_crypto_srandom();
gethostname(hostbuf, sizeof(hostbuf) - 1);
hostbuf[COUNTOF(hostbuf) - 1] = '\0';
hostname = hostbuf;
groupname = hostbuf;
passwd1 = hostbuf;
passwd2 = NULL;
GETTIMEOFDAY(&tv, NULL);
epoch = tv.tv_sec;
fstamp = (u_int)(epoch + JAN_1970);
optct = ntpOptionProcess(&ntp_keygenOptions, argc, argv);
argc -= optct; argv += optct;
(void)argc;
(void)argv;
#ifdef OPENSSL
if (SSLeay() == SSLEAY_VERSION_NUMBER)
fprintf(stderr, "Using OpenSSL version %s\n",
SSLeay_version(SSLEAY_VERSION));
else
fprintf(stderr, "Built against OpenSSL %s, using version %s\n",
OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
#endif
debug = OPT_VALUE_SET_DEBUG_LEVEL;
if (HAVE_OPT( MD5KEY ))
md5key++;
#ifdef AUTOKEY
if (HAVE_OPT( PASSWORD ))
passwd1 = estrdup(OPT_ARG( PASSWORD ));
if (HAVE_OPT( EXPORT_PASSWD ))
passwd2 = estrdup(OPT_ARG( EXPORT_PASSWD ));
if (HAVE_OPT( HOST_KEY ))
hostkey++;
if (HAVE_OPT( SIGN_KEY ))
sign = estrdup(OPT_ARG( SIGN_KEY ));
if (HAVE_OPT( GQ_PARAMS ))
gqkey++;
if (HAVE_OPT( IFFKEY ))
iffkey++;
if (HAVE_OPT( MV_PARAMS )) {
mvkey++;
nkeys = OPT_VALUE_MV_PARAMS;
}
if (HAVE_OPT( MV_KEYS )) {
mvpar++;
nkeys = OPT_VALUE_MV_KEYS;
}
if (HAVE_OPT( IMBITS ))
modulus2 = OPT_VALUE_IMBITS;
if (HAVE_OPT( MODULUS ))
modulus = OPT_VALUE_MODULUS;
if (HAVE_OPT( CERTIFICATE ))
scheme = OPT_ARG( CERTIFICATE );
if (HAVE_OPT( CIPHER ))
ciphername = OPT_ARG( CIPHER );
if (HAVE_OPT( SUBJECT_NAME ))
hostname = estrdup(OPT_ARG( SUBJECT_NAME ));
if (HAVE_OPT( IDENT ))
groupname = estrdup(OPT_ARG( IDENT ));
if (HAVE_OPT( LIFETIME ))
lifetime = OPT_VALUE_LIFETIME;
if (HAVE_OPT( PVT_CERT ))
exten = EXT_KEY_PRIVATE;
if (HAVE_OPT( TRUSTED_CERT ))
exten = EXT_KEY_TRUST;
if (hostname != hostbuf)
ptr = strchr(hostname, '@');
else
ptr = NULL;
if (ptr != NULL) {
*ptr = '\0';
groupname = estrdup(ptr + 1);
if (ptr == hostname)
hostname = hostbuf;
}
if (groupname == hostbuf) {
certname = hostname;
} else {
snprintf(certnamebuf, sizeof(certnamebuf), "%s@%s",
hostname, groupname);
certname = certnamebuf;
}
ERR_load_crypto_strings();
OpenSSL_add_all_algorithms();
if (!RAND_status()) {
if (RAND_file_name(pathbuf, sizeof(pathbuf)) == NULL) {
fprintf(stderr, "RAND_file_name %s\n",
ERR_error_string(ERR_get_error(), NULL));
exit (-1);
}
temp = RAND_load_file(pathbuf, -1);
if (temp == 0) {
fprintf(stderr,
"RAND_load_file %s not found or empty\n",
pathbuf);
exit (-1);
}
fprintf(stderr,
"Random seed file %s %u bytes\n", pathbuf, temp);
RAND_add(&epoch, sizeof(epoch), 4.0);
}
#endif
if (md5key) {
gen_md5("md5");
exit (0);
}
#ifdef AUTOKEY
snprintf(filename, sizeof(filename), "ntpkey_cert_%s", hostname);
if ((fstr = fopen(filename, "r")) != NULL) {
cert = PEM_read_X509(fstr, NULL, NULL, NULL);
fclose(fstr);
}
if (cert != NULL) {
X509_NAME_oneline(X509_get_subject_name(cert), groupbuf,
MAXFILENAME);
if (scheme == NULL) {
nid = OBJ_obj2nid(cert->cert_info->
signature->algorithm);
scheme = OBJ_nid2sn(nid);
}
if (exten == NULL) {
ptr = strstr(groupbuf, "CN=");
cnt = X509_get_ext_count(cert);
for (i = 0; i < cnt; i++) {
ext = X509_get_ext(cert, i);
if (OBJ_obj2nid(ext->object) ==
NID_ext_key_usage) {
bp = BIO_new(BIO_s_mem());
X509V3_EXT_print(bp, ext, 0, 0);
BIO_gets(bp, pathbuf,
MAXFILENAME);
BIO_free(bp);
if (strcmp(pathbuf,
"Trust Root") == 0)
exten = EXT_KEY_TRUST;
else if (strcmp(pathbuf,
"Private") == 0)
exten = EXT_KEY_PRIVATE;
certname = estrdup(ptr + 3);
}
}
}
}
if (scheme == NULL)
scheme = "RSA-MD5";
if (ciphername == NULL)
ciphername = "des-ede3-cbc";
cipher = EVP_get_cipherbyname(ciphername);
if (cipher == NULL) {
fprintf(stderr, "Unknown cipher %s\n", ciphername);
exit(-1);
}
fprintf(stderr, "Using host %s group %s\n", hostname,
groupname);
if (hostkey)
pkey_host = genkey("RSA", "host");
if (pkey_host == NULL) {
snprintf(filename, sizeof(filename), "ntpkey_host_%s", hostname);
pkey_host = readkey(filename, passwd1, &fstamp, NULL);
if (pkey_host != NULL) {
followlink(filename, sizeof(filename));
fprintf(stderr, "Using host key %s\n",
filename);
} else {
pkey_host = genkey("RSA", "host");
}
}
if (pkey_host == NULL) {
fprintf(stderr, "Generating host key fails\n");
exit(-1);
}
if (sign != NULL)
pkey_sign = genkey(sign, "sign");
if (pkey_sign == NULL) {
snprintf(filename, sizeof(filename), "ntpkey_sign_%s",
hostname);
pkey_sign = readkey(filename, passwd1, &fstamp, NULL);
if (pkey_sign != NULL) {
followlink(filename, sizeof(filename));
fprintf(stderr, "Using sign key %s\n",
filename);
} else {
pkey_sign = pkey_host;
fprintf(stderr, "Using host key as sign key\n");
}
}
if (gqkey)
pkey_gqkey = gen_gqkey("gqkey");
if (pkey_gqkey == NULL) {
snprintf(filename, sizeof(filename), "ntpkey_gqkey_%s",
groupname);
pkey_gqkey = readkey(filename, passwd1, &fstamp, NULL);
if (pkey_gqkey != NULL) {
followlink(filename, sizeof(filename));
fprintf(stderr, "Using GQ parameters %s\n",
filename);
}
}
if (pkey_gqkey != NULL)
grpkey = BN_bn2hex(pkey_gqkey->pkey.rsa->q);
if (pkey_gqkey != NULL && HAVE_OPT(ID_KEY)) {
RSA *rsa;
snprintf(filename, sizeof(filename),
"ntpkey_gqpar_%s.%u", groupname, fstamp);
fprintf(stderr, "Writing GQ parameters %s to stdout\n",
filename);
fprintf(stdout, "# %s\n# %s\n", filename,
ctime(&epoch));
rsa = pkey_gqkey->pkey.rsa;
BN_copy(rsa->p, BN_value_one());
BN_copy(rsa->q, BN_value_one());
pkey = EVP_PKEY_new();
EVP_PKEY_assign_RSA(pkey, rsa);
PEM_write_PKCS8PrivateKey(stdout, pkey, NULL, NULL, 0,
NULL, NULL);
fflush(stdout);
if (debug)
RSA_print_fp(stderr, rsa, 0);
}
if (pkey_gqkey != NULL && passwd2 != NULL) {
RSA *rsa;
snprintf(filename, sizeof(filename),
"ntpkey_gqkey_%s.%u", groupname, fstamp);
fprintf(stderr, "Writing GQ keys %s to stdout\n",
filename);
fprintf(stdout, "# %s\n# %s\n", filename,
ctime(&epoch));
rsa = pkey_gqkey->pkey.rsa;
pkey = EVP_PKEY_new();
EVP_PKEY_assign_RSA(pkey, rsa);
PEM_write_PKCS8PrivateKey(stdout, pkey, cipher, NULL, 0,
NULL, passwd2);
fflush(stdout);
if (debug)
RSA_print_fp(stderr, rsa, 0);
}
if (iffkey)
pkey_iffkey = gen_iffkey("iffkey");
if (pkey_iffkey == NULL) {
snprintf(filename, sizeof(filename), "ntpkey_iffkey_%s",
groupname);
pkey_iffkey = readkey(filename, passwd1, &fstamp, NULL);
if (pkey_iffkey != NULL) {
followlink(filename, sizeof(filename));
fprintf(stderr, "Using IFF keys %s\n",
filename);
}
}
if (pkey_iffkey != NULL && HAVE_OPT(ID_KEY)) {
DSA *dsa;
snprintf(filename, sizeof(filename),
"ntpkey_iffpar_%s.%u", groupname, fstamp);
fprintf(stderr, "Writing IFF parameters %s to stdout\n",
filename);
fprintf(stdout, "# %s\n# %s\n", filename,
ctime(&epoch));
dsa = pkey_iffkey->pkey.dsa;
BN_copy(dsa->priv_key, BN_value_one());
pkey = EVP_PKEY_new();
EVP_PKEY_assign_DSA(pkey, dsa);
PEM_write_PKCS8PrivateKey(stdout, pkey, NULL, NULL, 0,
NULL, NULL);
fflush(stdout);
if (debug)
DSA_print_fp(stderr, dsa, 0);
}
if (pkey_iffkey != NULL && passwd2 != NULL) {
DSA *dsa;
snprintf(filename, sizeof(filename),
"ntpkey_iffkey_%s.%u", groupname, fstamp);
fprintf(stderr, "Writing IFF keys %s to stdout\n",
filename);
fprintf(stdout, "# %s\n# %s\n", filename,
ctime(&epoch));
dsa = pkey_iffkey->pkey.dsa;
pkey = EVP_PKEY_new();
EVP_PKEY_assign_DSA(pkey, dsa);
PEM_write_PKCS8PrivateKey(stdout, pkey, cipher, NULL, 0,
NULL, passwd2);
fflush(stdout);
if (debug)
DSA_print_fp(stderr, dsa, 0);
}
if (mvkey)
pkey_mvkey = gen_mvkey("mv", pkey_mvpar);
if (pkey_mvkey == NULL) {
snprintf(filename, sizeof(filename), "ntpkey_mvta_%s",
groupname);
pkey_mvkey = readkey(filename, passwd1, &fstamp,
pkey_mvpar);
if (pkey_mvkey != NULL) {
followlink(filename, sizeof(filename));
fprintf(stderr, "Using MV keys %s\n",
filename);
}
}
if (pkey_mvkey != NULL && HAVE_OPT(ID_KEY)) {
snprintf(filename, sizeof(filename),
"ntpkey_mvpar_%s.%u", groupname, fstamp);
fprintf(stderr, "Writing MV parameters %s to stdout\n",
filename);
fprintf(stdout, "# %s\n# %s\n", filename,
ctime(&epoch));
pkey = pkey_mvpar[2];
PEM_write_PKCS8PrivateKey(stdout, pkey, NULL, NULL, 0,
NULL, NULL);
fflush(stdout);
if (debug)
DSA_print_fp(stderr, pkey->pkey.dsa, 0);
}
if (pkey_mvkey != NULL && passwd2 != NULL) {
snprintf(filename, sizeof(filename),
"ntpkey_mvkey_%s.%u", groupname, fstamp);
fprintf(stderr, "Writing MV keys %s to stdout\n",
filename);
fprintf(stdout, "# %s\n# %s\n", filename,
ctime(&epoch));
pkey = pkey_mvpar[1];
PEM_write_PKCS8PrivateKey(stdout, pkey, cipher, NULL, 0,
NULL, passwd2);
fflush(stdout);
if (debug)
DSA_print_fp(stderr, pkey->pkey.dsa, 0);
}
ectx = EVP_get_digestbyname(scheme);
if (ectx == NULL) {
fprintf(stderr,
"Invalid digest/signature combination %s\n",
scheme);
exit (-1);
}
x509(pkey_sign, ectx, grpkey, exten, certname);
#endif
exit(0);
}
int
gen_md5(
const char *id
)
{
u_char md5key[MD5SIZE + 1];
FILE *str;
int i, j;
#ifdef OPENSSL
u_char keystr[MD5SIZE];
u_char hexstr[2 * MD5SIZE + 1];
u_char hex[] = "0123456789abcdef";
#endif
str = fheader("MD5key", id, groupname);
for (i = 1; i <= MD5KEYS; i++) {
for (j = 0; j < MD5SIZE; j++) {
u_char temp;
while (1) {
int rc;
rc = ntp_crypto_random_buf(
&temp, sizeof(temp));
if (-1 == rc) {
fprintf(stderr, "ntp_crypto_random_buf() failed.\n");
exit (-1);
}
if (temp == '#')
continue;
if (temp > 0x20 && temp < 0x7f)
break;
}
md5key[j] = temp;
}
md5key[j] = '\0';
fprintf(str, "%2d MD5 %s # MD5 key\n", i,
md5key);
}
#ifdef OPENSSL
for (i = 1; i <= MD5KEYS; i++) {
RAND_bytes(keystr, 20);
for (j = 0; j < MD5SIZE; j++) {
hexstr[2 * j] = hex[keystr[j] >> 4];
hexstr[2 * j + 1] = hex[keystr[j] & 0xf];
}
hexstr[2 * MD5SIZE] = '\0';
fprintf(str, "%2d SHA1 %s # SHA1 key\n", i + MD5KEYS,
hexstr);
}
#endif
fclose(str);
return (1);
}
#ifdef AUTOKEY
EVP_PKEY *
readkey(
char *cp,
char *passwd,
u_int *estamp,
EVP_PKEY **evpars
)
{
FILE *str;
EVP_PKEY *pkey = NULL;
u_int gstamp;
char linkname[MAXFILENAME];
EVP_PKEY *parkey;
char *ptr;
int i;
str = fopen(cp, "r");
if (str == NULL)
return (NULL);
if ((ptr = fgets(linkname, MAXFILENAME, str)) == NULL) {
fprintf(stderr, "Empty key file %s\n", cp);
fclose(str);
return (NULL);
}
if ((ptr = strrchr(ptr, '.')) == NULL) {
fprintf(stderr, "No filestamp found in %s\n", cp);
fclose(str);
return (NULL);
}
if (sscanf(++ptr, "%u", &gstamp) != 1) {
fprintf(stderr, "Invalid filestamp found in %s\n", cp);
fclose(str);
return (NULL);
}
for (i = 0; i <= MVMAX - 1;) {
parkey = PEM_read_PrivateKey(str, NULL, NULL, passwd);
if (evpars != NULL) {
evpars[i++] = parkey;
evpars[i] = NULL;
}
if (parkey == NULL)
break;
if (pkey == NULL)
pkey = parkey;
if (debug) {
if (parkey->type == EVP_PKEY_DSA)
DSA_print_fp(stderr, parkey->pkey.dsa,
0);
else if (parkey->type == EVP_PKEY_RSA)
RSA_print_fp(stderr, parkey->pkey.rsa,
0);
}
}
fclose(str);
if (pkey == NULL) {
fprintf(stderr, "Corrupt file %s or wrong key %s\n%s\n",
cp, passwd, ERR_error_string(ERR_get_error(),
NULL));
exit (-1);
}
*estamp = gstamp;
return (pkey);
}
EVP_PKEY *
gen_rsa(
const char *id
)
{
EVP_PKEY *pkey;
RSA *rsa;
FILE *str;
fprintf(stderr, "Generating RSA keys (%d bits)...\n", modulus);
rsa = RSA_generate_key(modulus, 65537, cb, _UC("RSA"));
fprintf(stderr, "\n");
if (rsa == NULL) {
fprintf(stderr, "RSA generate keys fails\n%s\n",
ERR_error_string(ERR_get_error(), NULL));
return (NULL);
}
if (!RSA_check_key(rsa)) {
fprintf(stderr, "Invalid RSA key\n%s\n",
ERR_error_string(ERR_get_error(), NULL));
RSA_free(rsa);
return (NULL);
}
if (strcmp(id, "sign") == 0)
str = fheader("RSAsign", id, hostname);
else
str = fheader("RSAhost", id, hostname);
pkey = EVP_PKEY_new();
EVP_PKEY_assign_RSA(pkey, rsa);
PEM_write_PKCS8PrivateKey(str, pkey, cipher, NULL, 0, NULL,
passwd1);
fclose(str);
if (debug)
RSA_print_fp(stderr, rsa, 0);
return (pkey);
}
EVP_PKEY *
gen_dsa(
const char *id
)
{
EVP_PKEY *pkey;
DSA *dsa;
u_char seed[20];
FILE *str;
fprintf(stderr,
"Generating DSA parameters (%d bits)...\n", modulus);
RAND_bytes(seed, sizeof(seed));
dsa = DSA_generate_parameters(modulus, seed, sizeof(seed), NULL,
NULL, cb, _UC("DSA"));
fprintf(stderr, "\n");
if (dsa == NULL) {
fprintf(stderr, "DSA generate parameters fails\n%s\n",
ERR_error_string(ERR_get_error(), NULL));
return (NULL);
}
fprintf(stderr, "Generating DSA keys (%d bits)...\n", modulus);
if (!DSA_generate_key(dsa)) {
fprintf(stderr, "DSA generate keys fails\n%s\n",
ERR_error_string(ERR_get_error(), NULL));
DSA_free(dsa);
return (NULL);
}
str = fheader("DSAsign", id, hostname);
pkey = EVP_PKEY_new();
EVP_PKEY_assign_DSA(pkey, dsa);
PEM_write_PKCS8PrivateKey(str, pkey, cipher, NULL, 0, NULL,
passwd1);
fclose(str);
if (debug)
DSA_print_fp(stderr, dsa, 0);
return (pkey);
}
EVP_PKEY *
gen_iffkey(
const char *id
)
{
EVP_PKEY *pkey;
DSA *dsa;
u_char seed[20];
BN_CTX *ctx;
BIGNUM *b, *r, *k, *u, *v, *w;
FILE *str;
u_int temp;
fprintf(stderr, "Generating IFF keys (%d bits)...\n",
modulus2);
RAND_bytes(seed, sizeof(seed));
dsa = DSA_generate_parameters(modulus2, seed, sizeof(seed), NULL,
NULL, cb, _UC("IFF"));
fprintf(stderr, "\n");
if (dsa == NULL) {
fprintf(stderr, "DSA generate parameters fails\n%s\n",
ERR_error_string(ERR_get_error(), NULL));
return (NULL);;
}
b = BN_new(); r = BN_new(); k = BN_new();
u = BN_new(); v = BN_new(); w = BN_new(); ctx = BN_CTX_new();
BN_rand(b, BN_num_bits(dsa->q), -1, 0);
BN_mod(b, b, dsa->q, ctx);
BN_sub(v, dsa->q, b);
BN_mod_exp(v, dsa->g, v, dsa->p, ctx);
BN_mod_exp(u, dsa->g, b, dsa->p, ctx);
BN_mod_mul(u, u, v, dsa->p, ctx);
temp = BN_is_one(u);
fprintf(stderr,
"Confirm g^(q - b) g^b = 1 mod p: %s\n", temp == 1 ?
"yes" : "no");
if (!temp) {
BN_free(b); BN_free(r); BN_free(k);
BN_free(u); BN_free(v); BN_free(w); BN_CTX_free(ctx);
return (NULL);
}
dsa->priv_key = BN_dup(b);
dsa->pub_key = BN_dup(v);
BN_rand(r, BN_num_bits(dsa->q), -1, 0);
BN_mod(r, r, dsa->q, ctx);
BN_rand(k, BN_num_bits(dsa->q), -1, 0);
BN_mod(k, k, dsa->q, ctx);
BN_mod_mul(v, dsa->priv_key, r, dsa->q, ctx);
BN_add(v, v, k);
BN_mod(v, v, dsa->q, ctx);
BN_mod_exp(u, dsa->g, k, dsa->p, ctx);
BN_mod_exp(v, dsa->g, v, dsa->p, ctx);
BN_mod_exp(w, dsa->pub_key, r, dsa->p, ctx);
BN_mod_mul(v, w, v, dsa->p, ctx);
temp = BN_cmp(u, v);
fprintf(stderr,
"Confirm g^k = g^(k + b r) g^(q - b) r: %s\n", temp ==
0 ? "yes" : "no");
BN_free(b); BN_free(r); BN_free(k);
BN_free(u); BN_free(v); BN_free(w); BN_CTX_free(ctx);
if (temp != 0) {
DSA_free(dsa);
return (NULL);
}
str = fheader("IFFkey", id, groupname);
pkey = EVP_PKEY_new();
EVP_PKEY_assign_DSA(pkey, dsa);
PEM_write_PKCS8PrivateKey(str, pkey, cipher, NULL, 0, NULL,
passwd1);
fclose(str);
if (debug)
DSA_print_fp(stderr, dsa, 0);
return (pkey);
}
EVP_PKEY *
gen_gqkey(
const char *id
)
{
EVP_PKEY *pkey;
RSA *rsa;
BN_CTX *ctx;
BIGNUM *u, *v, *g, *k, *r, *y;
FILE *str;
u_int temp;
fprintf(stderr,
"Generating GQ parameters (%d bits)...\n",
modulus2);
rsa = RSA_generate_key(modulus2, 65537, cb, _UC("GQ"));
fprintf(stderr, "\n");
if (rsa == NULL) {
fprintf(stderr, "RSA generate keys fails\n%s\n",
ERR_error_string(ERR_get_error(), NULL));
return (NULL);
}
u = BN_new(); v = BN_new(); g = BN_new();
k = BN_new(); r = BN_new(); y = BN_new();
ctx = BN_CTX_new();
BN_rand(rsa->e, BN_num_bits(rsa->n), -1, 0);
BN_mod(rsa->e, rsa->e, rsa->n, ctx);
BN_rand(u, BN_num_bits(rsa->n), -1, 0);
BN_mod(u, u, rsa->n, ctx);
BN_mod_inverse(v, u, rsa->n, ctx);
BN_mod_mul(k, v, u, rsa->n, ctx);
BN_mod_exp(v, v, rsa->e, rsa->n, ctx);
BN_mod_exp(g, u, rsa->e, rsa->n, ctx);
BN_mod_mul(g, g, v, rsa->n, ctx);
temp = BN_is_one(g);
fprintf(stderr,
"Confirm u^b (u^-1)^b = 1 mod n: %s\n", temp ? "yes" :
"no");
if (!temp) {
BN_free(u); BN_free(v);
BN_free(g); BN_free(k); BN_free(r); BN_free(y);
BN_CTX_free(ctx);
RSA_free(rsa);
return (NULL);
}
BN_copy(rsa->p, u);
BN_copy(rsa->q, v);
BN_rand(r, BN_num_bits(rsa->n), -1, 0);
BN_mod(r, r, rsa->n, ctx);
BN_rand(k, BN_num_bits(rsa->n), -1, 0);
BN_mod(k, k, rsa->n, ctx);
BN_mod_exp(y, rsa->p, r, rsa->n, ctx);
BN_mod_mul(y, k, y, rsa->n, ctx);
BN_mod_exp(g, k, rsa->e, rsa->n, ctx);
BN_mod_exp(v, rsa->q, r, rsa->n, ctx);
BN_mod_exp(y, y, rsa->e, rsa->n, ctx);
BN_mod_mul(y, v, y, rsa->n, ctx);
temp = BN_cmp(y, g);
fprintf(stderr, "Confirm g^k = v^r y^b mod n: %s\n", temp == 0 ?
"yes" : "no");
BN_CTX_free(ctx); BN_free(u); BN_free(v);
BN_free(g); BN_free(k); BN_free(r); BN_free(y);
if (temp != 0) {
RSA_free(rsa);
return (NULL);
}
BN_copy(rsa->d, BN_value_one());
BN_copy(rsa->dmp1, BN_value_one());
BN_copy(rsa->dmq1, BN_value_one());
BN_copy(rsa->iqmp, BN_value_one());
str = fheader("GQkey", id, groupname);
pkey = EVP_PKEY_new();
EVP_PKEY_assign_RSA(pkey, rsa);
PEM_write_PKCS8PrivateKey(str, pkey, cipher, NULL, 0, NULL,
passwd1);
fclose(str);
if (debug)
RSA_print_fp(stderr, rsa, 0);
return (pkey);
}
EVP_PKEY *
gen_mvkey(
const char *id,
EVP_PKEY **evpars
)
{
EVP_PKEY *pkey, *pkey1;
DSA *dsa, *dsa2, *sdsa;
BN_CTX *ctx;
BIGNUM *a[MVMAX];
BIGNUM *g[MVMAX];
BIGNUM *s1[MVMAX];
BIGNUM *x[MVMAX];
BIGNUM *xbar[MVMAX], *xhat[MVMAX];
BIGNUM *b;
BIGNUM *b1;
BIGNUM *s;
BIGNUM *biga;
BIGNUM *bige;
BIGNUM *gbar, *ghat;
BIGNUM *u, *v, *w;
int i, j, n;
FILE *str;
u_int temp;
n = nkeys;
fprintf(stderr,
"Generating MV parameters for %d keys (%d bits)...\n", n,
modulus2 / n);
ctx = BN_CTX_new(); u = BN_new(); v = BN_new(); w = BN_new();
b = BN_new(); b1 = BN_new();
dsa = DSA_new();
dsa->p = BN_new(); dsa->q = BN_new(); dsa->g = BN_new();
dsa->priv_key = BN_new(); dsa->pub_key = BN_new();
temp = 0;
for (j = 1; j <= n; j++) {
s1[j] = BN_new();
while (1) {
BN_generate_prime(s1[j], modulus2 / n, 0, NULL,
NULL, NULL, NULL);
for (i = 1; i < j; i++) {
if (BN_cmp(s1[i], s1[j]) == 0)
break;
}
if (i == j)
break;
temp++;
}
}
fprintf(stderr, "Birthday keys regenerated %d\n", temp);
temp = 0;
while (1) {
BN_one(dsa->q);
for (j = 1; j <= n; j++)
BN_mul(dsa->q, dsa->q, s1[j], ctx);
BN_copy(dsa->p, dsa->q);
BN_add(dsa->p, dsa->p, dsa->p);
BN_add_word(dsa->p, 1);
if (BN_is_prime(dsa->p, BN_prime_checks, NULL, ctx,
NULL))
break;
temp++;
j = temp % n + 1;
while (1) {
BN_generate_prime(u, modulus2 / n, 0, 0, NULL,
NULL, NULL);
for (i = 1; i <= n; i++) {
if (BN_cmp(u, s1[i]) == 0)
break;
}
if (i > n)
break;
}
BN_copy(s1[j], u);
}
fprintf(stderr, "Defective keys regenerated %d\n", temp);
BN_copy(v, dsa->p);
BN_sub_word(v, 1);
while (1) {
BN_rand(dsa->g, BN_num_bits(dsa->p) - 1, 0, 0);
BN_mod(dsa->g, dsa->g, dsa->p, ctx);
BN_gcd(u, dsa->g, v, ctx);
if (!BN_is_one(u))
continue;
BN_mod_exp(u, dsa->g, dsa->q, dsa->p, ctx);
if (BN_is_one(u))
break;
}
fprintf(stderr,
"Generating polynomial coefficients for %d roots (%d bits)\n",
n, BN_num_bits(dsa->q));
for (j = 1; j <= n; j++) {
x[j] = BN_new();
while (1) {
BN_rand(x[j], BN_num_bits(dsa->q), 0, 0);
BN_mod(x[j], x[j], dsa->q, ctx);
BN_gcd(u, x[j], dsa->q, ctx);
if (BN_is_one(u))
break;
}
}
for (i = 0; i <= n; i++) {
a[i] = BN_new();
BN_one(a[i]);
}
for (j = 1; j <= n; j++) {
BN_zero(w);
for (i = 0; i < j; i++) {
BN_copy(u, dsa->q);
BN_mod_mul(v, a[i], x[j], dsa->q, ctx);
BN_sub(u, u, v);
BN_add(u, u, w);
BN_copy(w, a[i]);
BN_mod(a[i], u, dsa->q, ctx);
}
}
for (i = 0; i <= n; i++) {
g[i] = BN_new();
BN_mod_exp(g[i], dsa->g, a[i], dsa->p, ctx);
}
temp = 1;
for (j = 1; j <= n; j++) {
BN_one(u);
for (i = 0; i <= n; i++) {
BN_set_word(v, i);
BN_mod_exp(v, x[j], v, dsa->q, ctx);
BN_mod_mul(v, v, a[i], dsa->q, ctx);
BN_mod_exp(v, dsa->g, v, dsa->p, ctx);
BN_mod_mul(u, u, v, dsa->p, ctx);
}
if (!BN_is_one(u))
temp = 0;
}
fprintf(stderr,
"Confirm prod(g[i]^(x[j]^i)) = 1 for all i, j: %s\n", temp ?
"yes" : "no");
if (!temp) {
return (NULL);
}
biga = BN_new();
BN_one(biga);
for (j = 1; j <= n; j++) {
for (i = 0; i < n; i++) {
BN_set_word(v, i);
BN_mod_exp(v, x[j], v, dsa->q, ctx);
BN_mod_exp(v, g[i], v, dsa->p, ctx);
BN_mod_mul(biga, biga, v, dsa->p, ctx);
}
}
while (1) {
BN_rand(b, BN_num_bits(dsa->q), 0, 0);
BN_mod(b, b, dsa->q, ctx);
BN_gcd(u, b, dsa->q, ctx);
if (BN_is_one(u))
break;
}
BN_mod_inverse(b1, b, dsa->q, ctx);
for (j = 1; j <= n; j++) {
xbar[j] = BN_new(); xhat[j] = BN_new();
BN_add(w, dsa->q, s1[j]);
BN_div(w, u, w, s1[j], ctx);
BN_zero(xbar[j]);
BN_set_word(v, n);
for (i = 1; i <= n; i++) {
if (i == j)
continue;
BN_mod_exp(u, x[i], v, dsa->q, ctx);
BN_add(xbar[j], xbar[j], u);
}
BN_mod_mul(xbar[j], xbar[j], b1, dsa->q, ctx);
BN_mod_exp(xhat[j], x[j], v, dsa->q, ctx);
BN_mod_mul(xhat[j], xhat[j], w, dsa->q, ctx);
}
s = BN_new();
BN_copy(s, dsa->q);
BN_div(s, u, s, s1[n], ctx);
bige = BN_new(); gbar = BN_new(); ghat = BN_new();
BN_mod_exp(bige, biga, s, dsa->p, ctx);
BN_mod_exp(gbar, dsa->g, s, dsa->p, ctx);
BN_mod_mul(v, s, b, dsa->q, ctx);
BN_mod_exp(ghat, dsa->g, v, dsa->p, ctx);
i = 0;
str = fheader("MVta", "mvta", groupname);
fprintf(stderr, "Generating MV trusted-authority keys\n");
BN_copy(dsa->priv_key, biga);
BN_copy(dsa->pub_key, b);
pkey = EVP_PKEY_new();
EVP_PKEY_assign_DSA(pkey, dsa);
PEM_write_PKCS8PrivateKey(str, pkey, cipher, NULL, 0, NULL,
passwd1);
evpars[i++] = pkey;
if (debug)
DSA_print_fp(stderr, dsa, 0);
fprintf(stderr, "Generating MV server keys\n");
dsa2 = DSA_new();
dsa2->p = BN_dup(dsa->p);
dsa2->q = BN_dup(dsa->q);
dsa2->g = BN_dup(bige);
dsa2->priv_key = BN_dup(gbar);
dsa2->pub_key = BN_dup(ghat);
pkey1 = EVP_PKEY_new();
EVP_PKEY_assign_DSA(pkey1, dsa2);
PEM_write_PKCS8PrivateKey(str, pkey1, cipher, NULL, 0, NULL,
passwd1);
evpars[i++] = pkey1;
if (debug)
DSA_print_fp(stderr, dsa2, 0);
fprintf(stderr, "Generating %d MV client keys\n", n);
for (j = 1; j <= n; j++) {
sdsa = DSA_new();
sdsa->p = BN_dup(dsa->p);
sdsa->q = BN_dup(BN_value_one());
sdsa->g = BN_dup(BN_value_one());
sdsa->priv_key = BN_dup(xbar[j]);
sdsa->pub_key = BN_dup(xhat[j]);
pkey1 = EVP_PKEY_new();
EVP_PKEY_set1_DSA(pkey1, sdsa);
PEM_write_PKCS8PrivateKey(str, pkey1, cipher, NULL, 0,
NULL, passwd1);
evpars[i++] = pkey1;
if (debug)
DSA_print_fp(stderr, sdsa, 0);
BN_mod_exp(v, dsa2->priv_key, sdsa->pub_key, dsa->p,
ctx);
BN_mod_exp(u, dsa2->pub_key, sdsa->priv_key, dsa->p,
ctx);
BN_mod_mul(u, u, v, dsa->p, ctx);
BN_mod_mul(u, u, bige, dsa->p, ctx);
if (!BN_is_one(u)) {
fprintf(stderr, "Revoke key %d\n", j);
continue;
}
}
evpars[i++] = NULL;
fclose(str);
for (i = 0; i <= n; i++) {
BN_free(a[i]); BN_free(g[i]);
}
for (j = 1; j <= n; j++) {
BN_free(x[j]); BN_free(xbar[j]); BN_free(xhat[j]);
BN_free(s1[j]);
}
return (pkey);
}
int
x509 (
EVP_PKEY *pkey,
const EVP_MD *md,
char *gqpub,
const char *exten,
char *name
)
{
X509 *cert;
X509_NAME *subj;
X509_EXTENSION *ex;
FILE *str;
ASN1_INTEGER *serial;
const char *id;
char pathbuf[MAXFILENAME + 1];
id = OBJ_nid2sn(md->pkey_type);
fprintf(stderr, "Generating new certificate %s %s\n", name, id);
cert = X509_new();
X509_set_version(cert, 2L);
serial = ASN1_INTEGER_new();
ASN1_INTEGER_set(serial, (long)epoch + JAN_1970);
X509_set_serialNumber(cert, serial);
ASN1_INTEGER_free(serial);
X509_time_adj(X509_get_notBefore(cert), 0L, &epoch);
X509_time_adj(X509_get_notAfter(cert), lifetime * SECSPERDAY, &epoch);
subj = X509_get_subject_name(cert);
X509_NAME_add_entry_by_txt(subj, "commonName", MBSTRING_ASC,
(u_char *)name, -1, -1, 0);
subj = X509_get_issuer_name(cert);
X509_NAME_add_entry_by_txt(subj, "commonName", MBSTRING_ASC,
(u_char *)name, -1, -1, 0);
if (!X509_set_pubkey(cert, pkey)) {
fprintf(stderr, "Assign certificate signing key fails\n%s\n",
ERR_error_string(ERR_get_error(), NULL));
X509_free(cert);
return (0);
}
fprintf(stderr, "%s: %s\n", LN_basic_constraints,
BASIC_CONSTRAINTS);
ex = X509V3_EXT_conf_nid(NULL, NULL, NID_basic_constraints,
_UC(BASIC_CONSTRAINTS));
if (!X509_add_ext(cert, ex, -1)) {
fprintf(stderr, "Add extension field fails\n%s\n",
ERR_error_string(ERR_get_error(), NULL));
return (0);
}
X509_EXTENSION_free(ex);
fprintf(stderr, "%s: %s\n", LN_key_usage, KEY_USAGE);
ex = X509V3_EXT_conf_nid(NULL, NULL, NID_key_usage, _UC(KEY_USAGE));
if (!X509_add_ext(cert, ex, -1)) {
fprintf(stderr, "Add extension field fails\n%s\n",
ERR_error_string(ERR_get_error(), NULL));
return (0);
}
X509_EXTENSION_free(ex);
if (gqpub != NULL) {
fprintf(stderr, "%s\n", LN_subject_key_identifier);
ex = X509V3_EXT_conf_nid(NULL, NULL,
NID_subject_key_identifier, gqpub);
if (!X509_add_ext(cert, ex, -1)) {
fprintf(stderr,
"Add extension field fails\n%s\n",
ERR_error_string(ERR_get_error(), NULL));
return (0);
}
X509_EXTENSION_free(ex);
}
if (exten != NULL) {
fprintf(stderr, "%s: %s\n", LN_ext_key_usage, exten);
ex = X509V3_EXT_conf_nid(NULL, NULL,
NID_ext_key_usage, _UC(exten));
if (!X509_add_ext(cert, ex, -1)) {
fprintf(stderr,
"Add extension field fails\n%s\n",
ERR_error_string(ERR_get_error(), NULL));
return (0);
}
X509_EXTENSION_free(ex);
}
X509_sign(cert, pkey, md);
if (X509_verify(cert, pkey) <= 0) {
fprintf(stderr, "Verify %s certificate fails\n%s\n", id,
ERR_error_string(ERR_get_error(), NULL));
X509_free(cert);
return (0);
}
snprintf(pathbuf, sizeof(pathbuf), "%scert", id);
str = fheader(pathbuf, "cert", hostname);
PEM_write_X509(str, cert);
fclose(str);
if (debug)
X509_print_fp(stderr, cert);
X509_free(cert);
return (1);
}
#if 0
u_long
asn2ntp (
ASN1_TIME *asn1time
)
{
char *v;
struct tm tm;
if (asn1time->length > 13)
return (-1);
v = (char *)asn1time->data;
tm.tm_year = (v[0] - '0') * 10 + v[1] - '0';
if (tm.tm_year < 50)
tm.tm_year += 100;
tm.tm_mon = (v[2] - '0') * 10 + v[3] - '0' - 1;
tm.tm_mday = (v[4] - '0') * 10 + v[5] - '0';
tm.tm_hour = (v[6] - '0') * 10 + v[7] - '0';
tm.tm_min = (v[8] - '0') * 10 + v[9] - '0';
tm.tm_sec = (v[10] - '0') * 10 + v[11] - '0';
tm.tm_wday = 0;
tm.tm_yday = 0;
tm.tm_isdst = 0;
return (mktime(&tm) + JAN_1970);
}
#endif
void
cb (
int n1,
int n2,
void *chr
)
{
switch (n1) {
case 0:
d0++;
fprintf(stderr, "%s %d %d %lu\r", (char *)chr, n1, n2,
d0);
break;
case 1:
d1++;
fprintf(stderr, "%s\t\t%d %d %lu\r", (char *)chr, n1,
n2, d1);
break;
case 2:
d2++;
fprintf(stderr, "%s\t\t\t\t%d %d %lu\r", (char *)chr,
n1, n2, d2);
break;
case 3:
d3++;
fprintf(stderr, "%s\t\t\t\t\t\t%d %d %lu\r",
(char *)chr, n1, n2, d3);
break;
}
}
EVP_PKEY *
genkey(
const char *type,
const char *id
)
{
if (type == NULL)
return (NULL);
if (strcmp(type, "RSA") == 0)
return (gen_rsa(id));
else if (strcmp(type, "DSA") == 0)
return (gen_dsa(id));
fprintf(stderr, "Invalid %s key type %s\n", id, type);
return (NULL);
}
#endif
FILE *
fheader (
const char *file,
const char *ulink,
const char *owner
)
{
FILE *str;
char linkname[MAXFILENAME];
int temp;
#ifdef HAVE_UMASK
mode_t orig_umask;
#endif
snprintf(filename, sizeof(filename), "ntpkey_%s_%s.%u", file,
owner, fstamp);
#ifdef HAVE_UMASK
orig_umask = umask( S_IWGRP | S_IRWXO );
str = fopen(filename, "w");
(void) umask(orig_umask);
#else
str = fopen(filename, "w");
#endif
if (str == NULL) {
perror("Write");
exit (-1);
}
if (strcmp(ulink, "md5") == 0) {
strcpy(linkname,"ntp.keys");
} else {
snprintf(linkname, sizeof(linkname), "ntpkey_%s_%s", ulink,
hostname);
}
(void)remove(linkname);
temp = symlink(filename, linkname);
if (temp < 0)
perror(file);
fprintf(stderr, "Generating new %s file and link\n", ulink);
fprintf(stderr, "%s->%s\n", linkname, filename);
fprintf(str, "# %s\n# %s\n", filename, ctime(&epoch));
return (str);
}