diff options
author | delphij <delphij@FreeBSD.org> | 2015-07-15 19:21:26 +0000 |
---|---|---|
committer | delphij <delphij@FreeBSD.org> | 2015-07-15 19:21:26 +0000 |
commit | 2a25cee78ab1d37e7d2bc40ae675646974d99f56 (patch) | |
tree | b0302ac4be59e104f4e1e54014561a1389397192 /contrib/ntp/ntpd/ntp_crypto.c | |
parent | a0741a75537b2e0514472ac3b28afc55a7846c30 (diff) | |
download | FreeBSD-src-2a25cee78ab1d37e7d2bc40ae675646974d99f56.zip FreeBSD-src-2a25cee78ab1d37e7d2bc40ae675646974d99f56.tar.gz |
MFC r280849,280915-280916,281015-281016,282097,282408,282415,283542,
284864,285169-285170,285435:
ntp 4.2.8p3.
Relnotes: yes
Approved by: re (?)
Diffstat (limited to 'contrib/ntp/ntpd/ntp_crypto.c')
-rw-r--r-- | contrib/ntp/ntpd/ntp_crypto.c | 3360 |
1 files changed, 1579 insertions, 1781 deletions
diff --git a/contrib/ntp/ntpd/ntp_crypto.c b/contrib/ntp/ntpd/ntp_crypto.c index e3f7afd..2be501d 100644 --- a/contrib/ntp/ntpd/ntp_crypto.c +++ b/contrib/ntp/ntpd/ntp_crypto.c @@ -5,8 +5,9 @@ #include <config.h> #endif -#ifdef OPENSSL +#ifdef AUTOKEY #include <stdio.h> +#include <stdlib.h> /* strtoul */ #include <sys/types.h> #include <sys/param.h> #include <unistd.h> @@ -16,7 +17,10 @@ #include "ntp_stdlib.h" #include "ntp_unixtime.h" #include "ntp_string.h" -#include <ntp_random.h> +#include "ntp_random.h" +#include "ntp_assert.h" +#include "ntp_calendar.h" +#include "ntp_leapsec.h" #include "openssl/asn1_mac.h" #include "openssl/bn.h" @@ -31,6 +35,33 @@ #endif /* KERNEL_PLL */ /* + * calcomp - compare two calendar structures, ignoring yearday and weekday; like strcmp + * No, it's not a plotter. If you don't understand that, you're too young. + */ +static int calcomp(struct calendar *pjd1, struct calendar *pjd2) +{ + int32_t diff; /* large enough to hold the signed difference between two uint16_t values */ + + diff = pjd1->year - pjd2->year; + if (diff < 0) return -1; else if (diff > 0) return 1; + /* same year; compare months */ + diff = pjd1->month - pjd2->month; + if (diff < 0) return -1; else if (diff > 0) return 1; + /* same year and month; compare monthday */ + diff = pjd1->monthday - pjd2->monthday; + if (diff < 0) return -1; else if (diff > 0) return 1; + /* same year and month and monthday; compare time */ + diff = pjd1->hour - pjd2->hour; + if (diff < 0) return -1; else if (diff > 0) return 1; + diff = pjd1->minute - pjd2->minute; + if (diff < 0) return -1; else if (diff > 0) return 1; + diff = pjd1->second - pjd2->second; + if (diff < 0) return -1; else if (diff > 0) return 1; + /* identical */ + return 0; +} + +/* * Extension field message format * * These are always signed and saved before sending in network byte @@ -40,7 +71,7 @@ * +-------+-------+ * | op | len | <- extension pointer * +-------+-------+ - * | assocID | + * | associd | * +---------------+ * | timestamp | <- value pointer * +---------------+ @@ -79,13 +110,28 @@ * creator or signor is synchronized to an authoritative source and * proventicated to a trusted authority. * - * Note there are four conditions required for server trust. First, the - * public key on the certificate must be verified, which involves a - * number of format, content and consistency checks. Next, the server - * identity must be confirmed by one of four schemes: private - * certificate, IFF scheme, GQ scheme or certificate trail hike to a - * self signed trusted certificate. Finally, the server signature must - * be verified. + * Note there are several conditions required for server trust. First, + * the public key on the server certificate must be verified, which can + * involve a hike along the certificate trail to a trusted host. Next, + * the server trust must be confirmed by one of several identity + * schemes. Valid cryptographic values are signed with attached + * timestamp and filestamp. Individual packet trust is confirmed + * relative to these values by a message digest with keys generated by a + * reverse-order pseudorandom hash. + * + * State decomposition. These flags are lit in the order given. They are + * dim only when the association is demobilized. + * + * CRYPTO_FLAG_ENAB Lit upon acceptance of a CRYPTO_ASSOC message + * CRYPTO_FLAG_CERT Lit when a self-digned trusted certificate is + * accepted. + * CRYPTO_FLAG_VRFY Lit when identity is confirmed. + * CRYPTO_FLAG_PROV Lit when the first signature is verified. + * CRYPTO_FLAG_COOK Lit when a valid cookie is accepted. + * CRYPTO_FLAG_AUTO Lit when valid autokey values are accepted. + * CRYPTO_FLAG_SIGN Lit when the server signed certificate is + * accepted. + * CRYPTO_FLAG_LEAP Lit when the leapsecond values are accepted. */ /* * Cryptodefines @@ -100,20 +146,24 @@ * Global cryptodata in host byte order */ u_int32 crypto_flags = 0x0; /* status word */ +int crypto_nid = KEY_TYPE_MD5; /* digest nid */ +char *sys_hostname = NULL; +char *sys_groupname = NULL; +static char *host_filename = NULL; /* host file name */ +static char *ident_filename = NULL; /* group file name */ /* * Global cryptodata in network byte order */ -struct cert_info *cinfo = NULL; /* certificate info/value */ +struct cert_info *cinfo = NULL; /* certificate info/value cache */ +struct cert_info *cert_host = NULL; /* host certificate */ +struct pkey_info *pkinfo = NULL; /* key info/value cache */ struct value hostval; /* host value */ struct value pubkey; /* public key */ -struct value tai_leap; /* leapseconds table */ -EVP_PKEY *iffpar_pkey = NULL; /* IFF parameters */ -EVP_PKEY *gqpar_pkey = NULL; /* GQ parameters */ -EVP_PKEY *mvpar_pkey = NULL; /* MV parameters */ -char *iffpar_file = NULL; /* IFF parameters file */ -char *gqpar_file = NULL; /* GQ parameters file */ -char *mvpar_file = NULL; /* MV parameters file */ +struct value tai_leap; /* leapseconds values */ +struct pkey_info *iffkey_info = NULL; /* IFF keys */ +struct pkey_info *gqkey_info = NULL; /* GQ keys */ +struct pkey_info *mvkey_info = NULL; /* MV keys */ /* * Private cryptodata in host byte order @@ -124,43 +174,34 @@ static EVP_PKEY *sign_pkey = NULL; /* sign key */ static const EVP_MD *sign_digest = NULL; /* sign digest */ static u_int sign_siglen; /* sign key length */ static char *rand_file = NULL; /* random seed file */ -static char *host_file = NULL; /* host key file */ -static char *sign_file = NULL; /* sign key file */ -static char *cert_file = NULL; /* certificate file */ -static char *leap_file = NULL; /* leapseconds file */ -static tstamp_t if_fstamp = 0; /* IFF filestamp */ -static tstamp_t gq_fstamp = 0; /* GQ file stamp */ -static tstamp_t mv_fstamp = 0; /* MV filestamp */ -static u_int ident_scheme = 0; /* server identity scheme */ /* * Cryptotypes */ -static int crypto_verify P((struct exten *, struct value *, - struct peer *)); -static int crypto_encrypt P((const u_char *, u_int, keyid_t *, - struct value *)); -static int crypto_alice P((struct peer *, struct value *)); -static int crypto_alice2 P((struct peer *, struct value *)); -static int crypto_alice3 P((struct peer *, struct value *)); -static int crypto_bob P((struct exten *, struct value *)); -static int crypto_bob2 P((struct exten *, struct value *)); -static int crypto_bob3 P((struct exten *, struct value *)); -static int crypto_iff P((struct exten *, struct peer *)); -static int crypto_gq P((struct exten *, struct peer *)); -static int crypto_mv P((struct exten *, struct peer *)); -static u_int crypto_send P((struct exten *, struct value *)); -static tstamp_t crypto_time P((void)); -static u_long asn2ntp P((ASN1_TIME *)); -static struct cert_info *cert_parse P((u_char *, u_int, tstamp_t)); -static int cert_sign P((struct exten *, struct value *)); -static int cert_valid P((struct cert_info *, EVP_PKEY *)); -static int cert_install P((struct exten *, struct peer *)); -static void cert_free P((struct cert_info *)); -static EVP_PKEY *crypto_key P((char *, tstamp_t *)); -static int bighash P((BIGNUM *, BIGNUM *)); -static struct cert_info *crypto_cert P((char *)); -static void crypto_tai P((char *)); +static int crypto_verify (struct exten *, struct value *, + struct peer *); +static int crypto_encrypt (const u_char *, u_int, keyid_t *, + struct value *); +static int crypto_alice (struct peer *, struct value *); +static int crypto_alice2 (struct peer *, struct value *); +static int crypto_alice3 (struct peer *, struct value *); +static int crypto_bob (struct exten *, struct value *); +static int crypto_bob2 (struct exten *, struct value *); +static int crypto_bob3 (struct exten *, struct value *); +static int crypto_iff (struct exten *, struct peer *); +static int crypto_gq (struct exten *, struct peer *); +static int crypto_mv (struct exten *, struct peer *); +static int crypto_send (struct exten *, struct value *, int); +static tstamp_t crypto_time (void); +static void asn_to_calendar (ASN1_TIME *, struct calendar*); +static struct cert_info *cert_parse (const u_char *, long, tstamp_t); +static int cert_sign (struct exten *, struct value *); +static struct cert_info *cert_install (struct exten *, struct peer *); +static int cert_hike (struct peer *, struct cert_info *); +static void cert_free (struct cert_info *); +static struct pkey_info *crypto_key (char *, char *, sockaddr_u *); +static void bighash (BIGNUM *, BIGNUM *); +static struct cert_info *crypto_cert (char *); #ifdef SYS_WINNT int @@ -177,12 +218,12 @@ readlink(char * link, char * file, int len) { * session key is the MD5 hash of these values, while the next key ID is * the first four octets of the hash. * - * Returns the next key ID + * Returns the next key ID or 0 if there is no destination address. */ keyid_t session_key( - struct sockaddr_storage *srcadr, /* source address */ - struct sockaddr_storage *dstadr, /* destination address */ + sockaddr_u *srcadr, /* source address */ + sockaddr_u *dstadr, /* destination address */ keyid_t keyno, /* key ID */ keyid_t private, /* private value */ u_long lifetime /* key lifetime */ @@ -202,41 +243,38 @@ session_key( * greater than zero, install the key and call it trusted. */ hdlen = 0; - switch(srcadr->ss_family) { + switch(AF(srcadr)) { case AF_INET: - header[0] = ((struct sockaddr_in *)srcadr)->sin_addr.s_addr; - header[1] = ((struct sockaddr_in *)dstadr)->sin_addr.s_addr; + header[0] = NSRCADR(srcadr); + header[1] = NSRCADR(dstadr); header[2] = htonl(keyno); header[3] = htonl(private); hdlen = 4 * sizeof(u_int32); break; case AF_INET6: - memcpy(&header[0], &GET_INADDR6(*srcadr), + memcpy(&header[0], PSOCK_ADDR6(srcadr), sizeof(struct in6_addr)); - memcpy(&header[4], &GET_INADDR6(*dstadr), + memcpy(&header[4], PSOCK_ADDR6(dstadr), sizeof(struct in6_addr)); header[8] = htonl(keyno); header[9] = htonl(private); hdlen = 10 * sizeof(u_int32); break; } - EVP_DigestInit(&ctx, EVP_md5()); + EVP_DigestInit(&ctx, EVP_get_digestbynid(crypto_nid)); EVP_DigestUpdate(&ctx, (u_char *)header, hdlen); EVP_DigestFinal(&ctx, dgst, &len); memcpy(&keyid, dgst, 4); keyid = ntohl(keyid); if (lifetime != 0) { - MD5auth_setkey(keyno, dgst, len); + MD5auth_setkey(keyno, crypto_nid, dgst, len); authtrust(keyno, lifetime); } -#ifdef DEBUG - if (debug > 1) - printf( - "session_key: %s > %s %08x %08x hash %08x life %lu\n", + DPRINTF(2, ("session_key: %s > %s %08x %08x hash %08x life %lu\n", stoa(srcadr), stoa(dstadr), keyno, - private, keyid, lifetime); -#endif + private, keyid, lifetime)); + return (keyid); } @@ -246,7 +284,7 @@ session_key( * * Returns * XEVNT_OK success - * XEVNT_PER host certificate expired + * XEVNT_ERR protocol error * * This routine constructs a pseudo-random sequence by repeatedly * hashing the session key starting from a given source address, @@ -266,28 +304,30 @@ make_keylist( struct value *vp; /* value pointer */ keyid_t keyid = 0; /* next key ID */ keyid_t cookie; /* private value */ - u_long lifetime; + long lifetime; u_int len, mpoll; int i; if (!dstadr) - return XEVNT_OK; + return XEVNT_ERR; /* * Allocate the key list if necessary. */ tstamp = crypto_time(); if (peer->keylist == NULL) - peer->keylist = emalloc(sizeof(keyid_t) * - NTP_MAXSESSION); + peer->keylist = eallocarray(NTP_MAXSESSION, + sizeof(keyid_t)); /* * Generate an initial key ID which is unique and greater than * NTP_MAXKEY. */ while (1) { - keyid = (ntp_random() + NTP_MAXKEY + 1) & ((1 << - sizeof(keyid_t)) - 1); + keyid = ntp_random() & 0xffffffff; + if (keyid <= NTP_MAXKEY) + continue; + if (authhavekey(keyid)) continue; break; @@ -301,7 +341,7 @@ make_keylist( * cookie if client mode or the host cookie if symmetric modes. */ mpoll = 1 << min(peer->ppoll, peer->hpoll); - lifetime = min(sys_automax, NTP_MAXSESSION * mpoll); + lifetime = min(1U << sys_automax, NTP_MAXSESSION * mpoll); if (peer->hmode == MODE_BROADCAST) cookie = 0; else @@ -310,10 +350,10 @@ make_keylist( peer->keylist[i] = keyid; peer->keynumber = i; keyid = session_key(&dstadr->sin, &peer->srcadr, keyid, - cookie, lifetime); + cookie, lifetime + mpoll); lifetime -= mpoll; if (auth_havekey(keyid) || keyid <= NTP_MAXKEY || - lifetime <= mpoll) + lifetime < 0 || tstamp == 0) break; } @@ -334,27 +374,20 @@ make_keylist( vp->vallen = htonl(sizeof(struct autokey)); vp->siglen = 0; if (tstamp != 0) { - if (tstamp < cinfo->first || tstamp > cinfo->last) - return (XEVNT_PER); - if (vp->sig == NULL) vp->sig = emalloc(sign_siglen); EVP_SignInit(&ctx, sign_digest); EVP_SignUpdate(&ctx, (u_char *)vp, 12); EVP_SignUpdate(&ctx, vp->ptr, sizeof(struct autokey)); - if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) + if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) { + NTP_INSIST(len <= sign_siglen); vp->siglen = htonl(len); - else - msyslog(LOG_ERR, "make_keys %s\n", - ERR_error_string(ERR_get_error(), NULL)); - peer->flags |= FLAG_ASSOC; + peer->flags |= FLAG_ASSOC; + } } -#ifdef DEBUG - if (debug) - printf("make_keys: %d %08x %08x ts %u fs %u poll %d\n", - ntohl(ap->seq), ntohl(ap->key), cookie, - ntohl(vp->tstamp), ntohl(vp->fstamp), peer->hpoll); -#endif + DPRINTF(1, ("make_keys: %d %08x %08x ts %u fs %u poll %d\n", + peer->keynumber, keyid, cookie, ntohl(vp->tstamp), + ntohl(vp->fstamp), peer->hpoll)); return (XEVNT_OK); } @@ -369,6 +402,11 @@ make_keylist( * valid length and is verified. There are a few cases where some values * are believed even if the signature fails, but only if the proventic * bit is not set. + * + * Returns + * XEVNT_OK success + * XEVNT_ERR protocol error + * XEVNT_LEN bad field format or length */ int crypto_recv( @@ -380,10 +418,10 @@ crypto_recv( u_int32 *pkt; /* receive packet pointer */ struct autokey *ap, *bp; /* autokey pointer */ struct exten *ep, *fp; /* extension pointers */ + struct cert_info *xinfo; /* certificate info pointer */ int has_mac; /* length of MAC field */ int authlen; /* offset of MAC field */ associd_t associd; /* association ID */ - tstamp_t tstamp = 0; /* timestamp */ tstamp_t fstamp = 0; /* filestamp */ u_int len; /* extension field length */ u_int code; /* extension field opcode */ @@ -393,7 +431,7 @@ crypto_recv( keyid_t cookie; /* crumbles */ int hismode; /* packet mode */ int rval = XEVNT_OK; - u_char *ptr; + const u_char *puch; u_int32 temp32; /* @@ -408,43 +446,28 @@ crypto_recv( */ authlen = LEN_PKT_NOMAC; hismode = (int)PKT_MODE((&rbufp->recv_pkt)->li_vn_mode); - while ((has_mac = rbufp->recv_length - authlen) > MAX_MAC_LEN) { + while ((has_mac = rbufp->recv_length - authlen) > (int)MAX_MAC_LEN) { pkt = (u_int32 *)&rbufp->recv_pkt + authlen / 4; ep = (struct exten *)pkt; code = ntohl(ep->opcode) & 0xffff0000; len = ntohl(ep->opcode) & 0x0000ffff; - associd = (associd_t) ntohl(pkt[1]); + // HMS: Why pkt[1] instead of ep->associd ? + associd = (associd_t)ntohl(pkt[1]); rval = XEVNT_OK; -#ifdef DEBUG - if (debug) - printf( - "crypto_recv: flags 0x%x ext offset %d len %u code 0x%x assocID %d\n", + DPRINTF(1, ("crypto_recv: flags 0x%x ext offset %d len %u code 0x%x associd %d\n", peer->crypto, authlen, len, code >> 16, - associd); -#endif + associd)); /* * Check version number and field length. If bad, * quietly ignore the packet. */ if (((code >> 24) & 0x3f) != CRYPTO_VN || len < 8) { - sys_unknownversion++; + sys_badlength++; code |= CRYPTO_ERROR; } - /* - * Little vulnerability bandage here. If a perp tosses a - * fake association ID over the fence, we better toss it - * out. Only the first one counts. - */ - if (code & CRYPTO_RESP) { - if (peer->assoc == 0) - peer->assoc = associd; - else if (peer->assoc != associd) - code |= CRYPTO_ERROR; - } if (len >= VALUE_LEN) { - tstamp = ntohl(ep->tstamp); fstamp = ntohl(ep->fstamp); vallen = ntohl(ep->vallen); /* @@ -469,19 +492,26 @@ crypto_recv( case CRYPTO_ASSOC: /* - * If the machine is running when this message - * arrives, the other fellow has reset and so - * must we. Otherwise, pass the extension field - * to the transmit side. + * If our state machine is running when this + * message arrives, the other fellow might have + * restarted. However, this could be an + * intruder, so just clamp the poll interval and + * find out for ourselves. Otherwise, pass the + * extension field to the transmit side. */ - if (peer->crypto) { + if (peer->crypto & CRYPTO_FLAG_CERT) { rval = XEVNT_ERR; break; } + if (peer->cmmd) { + if (peer->assoc != associd) { + rval = XEVNT_ERR; + break; + } + } fp = emalloc(len); memcpy(fp, ep, len); - temp32 = CRYPTO_RESP; - fp->opcode |= htonl(temp32); + fp->associd = htonl(peer->associd); peer->cmmd = fp; /* fall through */ @@ -491,67 +521,52 @@ crypto_recv( * Discard the message if it has already been * stored or the message has been amputated. */ - if (peer->crypto) + if (peer->crypto) { + if (peer->assoc != associd) + rval = XEVNT_ERR; break; - + } + INSIST(len >= VALUE_LEN); if (vallen == 0 || vallen > MAXHOSTNAME || len - VALUE_LEN < vallen) { rval = XEVNT_LEN; break; } + DPRINTF(1, ("crypto_recv: ident host 0x%x %d server 0x%x %d\n", + crypto_flags, peer->associd, fstamp, + peer->assoc)); + temp32 = crypto_flags & CRYPTO_FLAG_MASK; /* - * Check the identity schemes are compatible. If - * the client has PC, the server must have PC, - * in which case the server public key and - * identity are presumed valid, so we skip the - * certificate and identity exchanges and move - * immediately to the cookie exchange which - * confirms the server signature. + * If the client scheme is PC, the server scheme + * must be PC. The public key and identity are + * presumed valid, so we skip the certificate + * and identity exchanges and move immediately + * to the cookie exchange which confirms the + * server signature. */ -#ifdef DEBUG - if (debug) - printf( - "crypto_recv: ident host 0x%x server 0x%x\n", - crypto_flags, fstamp); -#endif - temp32 = (crypto_flags | ident_scheme) & - fstamp & CRYPTO_FLAG_MASK; if (crypto_flags & CRYPTO_FLAG_PRIV) { if (!(fstamp & CRYPTO_FLAG_PRIV)) { rval = XEVNT_KEY; break; - - } else { - fstamp |= CRYPTO_FLAG_VALID | - CRYPTO_FLAG_VRFY | - CRYPTO_FLAG_SIGN; } - /* - * In symmetric modes it is an error if either - * peer requests identity and the other peer - * does not support it. - */ - } else if ((hismode == MODE_ACTIVE || hismode == - MODE_PASSIVE) && ((crypto_flags | fstamp) & - CRYPTO_FLAG_MASK) && !temp32) { - rval = XEVNT_KEY; - break; - /* - * It is an error if the client requests - * identity and the server does not support it. - */ - } else if (hismode == MODE_CLIENT && (fstamp & - CRYPTO_FLAG_MASK) && !temp32) { - rval = XEVNT_KEY; - break; - } + fstamp |= CRYPTO_FLAG_CERT | + CRYPTO_FLAG_VRFY | CRYPTO_FLAG_SIGN; /* - * Otherwise, the identity scheme(s) are those - * that both client and server support. + * It is an error if either peer supports + * identity, but the other does not. */ - fstamp = temp32 | (fstamp & ~CRYPTO_FLAG_MASK); + } else if (hismode == MODE_ACTIVE || hismode == + MODE_PASSIVE) { + if ((temp32 && !(fstamp & + CRYPTO_FLAG_MASK)) || + (!temp32 && (fstamp & + CRYPTO_FLAG_MASK))) { + rval = XEVNT_KEY; + break; + } + } /* * Discard the message if the signature digest @@ -567,24 +582,32 @@ crypto_recv( /* * Save status word, host name and message - * digest/signature type. + * digest/signature type. If this is from a + * broadcast and the association ID has changed, + * request the autokey values. */ + peer->assoc = associd; + if (hismode == MODE_SERVER) + fstamp |= CRYPTO_FLAG_AUTO; + if (!(fstamp & CRYPTO_FLAG_TAI)) + fstamp |= CRYPTO_FLAG_LEAP; + RAND_bytes((u_char *)&peer->hcookie, 4); peer->crypto = fstamp; peer->digest = dp; + if (peer->subject != NULL) + free(peer->subject); peer->subject = emalloc(vallen + 1); memcpy(peer->subject, ep->pkt, vallen); peer->subject[vallen] = '\0'; - peer->issuer = emalloc(vallen + 1); - strcpy(peer->issuer, peer->subject); - temp32 = (fstamp >> 16) & 0xffff; - snprintf(statstr, NTP_MAXSTRLEN, - "flags 0x%x host %s signature %s", fstamp, - peer->subject, OBJ_nid2ln(temp32)); + if (peer->issuer != NULL) + free(peer->issuer); + peer->issuer = estrdup(peer->subject); + snprintf(statstr, sizeof(statstr), + "assoc %d %d host %s %s", peer->associd, + peer->assoc, peer->subject, + OBJ_nid2ln(temp32)); record_crypto_stats(&peer->srcadr, statstr); -#ifdef DEBUG - if (debug) - printf("crypto_recv: %s\n", statstr); -#endif + DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* @@ -597,8 +620,11 @@ crypto_recv( case CRYPTO_CERT | CRYPTO_RESP: /* - * Discard the message if invalid. + * Discard the message if empty or invalid. */ + if (len < VALUE_LEN) + break; + if ((rval = crypto_verify(ep, NULL, peer)) != XEVNT_OK) break; @@ -606,26 +632,16 @@ crypto_recv( /* * Scan the certificate list to delete old * versions and link the newest version first on - * the list. + * the list. Then, verify the signature. If the + * certificate is bad or missing, just ignore + * it. */ - if ((rval = cert_install(ep, peer)) != XEVNT_OK) + if ((xinfo = cert_install(ep, peer)) == NULL) { + rval = XEVNT_CRT; + break; + } + if ((rval = cert_hike(peer, xinfo)) != XEVNT_OK) break; - - /* - * If we snatch the certificate before the - * server certificate has been signed by its - * server, it will be self signed. When it is, - * we chase the certificate issuer, which the - * server has, and keep going until a self - * signed trusted certificate is found. Be sure - * to update the issuer field, since it may - * change. - */ - if (peer->issuer != NULL) - free(peer->issuer); - peer->issuer = emalloc(strlen(cinfo->issuer) + - 1); - strcpy(peer->issuer, cinfo->issuer); /* * We plug in the public key and lifetime from @@ -635,71 +651,58 @@ crypto_recv( * signature/digest NID. */ if (peer->pkey == NULL) { - ptr = (u_char *)cinfo->cert.ptr; - cert = d2i_X509(NULL, &ptr, - ntohl(cinfo->cert.vallen)); + puch = xinfo->cert.ptr; + cert = d2i_X509(NULL, &puch, + ntohl(xinfo->cert.vallen)); peer->pkey = X509_get_pubkey(cert); X509_free(cert); } peer->flash &= ~TEST8; - temp32 = cinfo->nid; - snprintf(statstr, NTP_MAXSTRLEN, - "cert %s 0x%x %s (%u) fs %u", - cinfo->subject, cinfo->flags, + temp32 = xinfo->nid; + snprintf(statstr, sizeof(statstr), + "cert %s %s 0x%x %s (%u) fs %u", + xinfo->subject, xinfo->issuer, xinfo->flags, OBJ_nid2ln(temp32), temp32, ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); -#ifdef DEBUG - if (debug) - printf("crypto_recv: %s\n", statstr); -#endif + DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* - * Schnorr (IFF)identity scheme. This scheme is designed - * for use with shared secret group keys and where the - * certificate may be generated by a third party. The - * client sends a challenge to the server, which - * performs a calculation and returns the result. A - * positive result is possible only if both client and + * Schnorr (IFF) identity scheme. This scheme is + * designed for use with shared secret server group keys + * and where the certificate may be generated by a third + * party. The client sends a challenge to the server, + * which performs a calculation and returns the result. + * A positive result is possible only if both client and * server contain the same secret group key. */ case CRYPTO_IFF | CRYPTO_RESP: /* - * Discard the message if invalid or certificate - * trail not trusted. + * Discard the message if invalid. */ - if (!(peer->crypto & CRYPTO_FLAG_VALID)) { - rval = XEVNT_ERR; - break; - } if ((rval = crypto_verify(ep, NULL, peer)) != XEVNT_OK) break; /* - * If the the challenge matches the response, - * the certificate public key, as well as the - * server public key, signatyre and identity are + * If the challenge matches the response, the + * server public key, signature and identity are * all verified at the same time. The server is * declared trusted, so we skip further - * certificate stages and move immediately to - * the cookie stage. + * certificate exchanges and move immediately to + * the cookie exchange. */ if ((rval = crypto_iff(ep, peer)) != XEVNT_OK) break; - peer->crypto |= CRYPTO_FLAG_VRFY | - CRYPTO_FLAG_PROV; + peer->crypto |= CRYPTO_FLAG_VRFY; peer->flash &= ~TEST8; - snprintf(statstr, NTP_MAXSTRLEN, "iff fs %u", - ntohl(ep->fstamp)); + snprintf(statstr, sizeof(statstr), "iff %s fs %u", + peer->issuer, ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); -#ifdef DEBUG - if (debug) - printf("crypto_recv: %s\n", statstr); -#endif + DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* @@ -715,136 +718,68 @@ crypto_recv( case CRYPTO_GQ | CRYPTO_RESP: /* - * Discard the message if invalid or certificate - * trail not trusted. + * Discard the message if invalid */ - if (!(peer->crypto & CRYPTO_FLAG_VALID)) { - rval = XEVNT_ERR; - break; - } if ((rval = crypto_verify(ep, NULL, peer)) != XEVNT_OK) break; /* - * If the the challenge matches the response, - * the certificate public key, as well as the - * server public key, signatyre and identity are + * If the challenge matches the response, the + * server public key, signature and identity are * all verified at the same time. The server is * declared trusted, so we skip further - * certificate stages and move immediately to - * the cookie stage. + * certificate exchanges and move immediately to + * the cookie exchange. */ if ((rval = crypto_gq(ep, peer)) != XEVNT_OK) break; - peer->crypto |= CRYPTO_FLAG_VRFY | - CRYPTO_FLAG_PROV; + peer->crypto |= CRYPTO_FLAG_VRFY; peer->flash &= ~TEST8; - snprintf(statstr, NTP_MAXSTRLEN, "gq fs %u", - ntohl(ep->fstamp)); + snprintf(statstr, sizeof(statstr), "gq %s fs %u", + peer->issuer, ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); -#ifdef DEBUG - if (debug) - printf("crypto_recv: %s\n", statstr); -#endif + DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* - * MV + * Mu-Varadharajan (MV) identity scheme. This scheme is + * designed for use with three levels of trust, trusted + * host, server and client. The trusted host key is + * opaque to servers and clients; the server keys are + * opaque to clients and each client key is different. + * Client keys can be revoked without requiring new key + * generations. */ case CRYPTO_MV | CRYPTO_RESP: /* - * Discard the message if invalid or certificate - * trail not trusted. + * Discard the message if invalid. */ - if (!(peer->crypto & CRYPTO_FLAG_VALID)) { - rval = XEVNT_ERR; - break; - } if ((rval = crypto_verify(ep, NULL, peer)) != XEVNT_OK) break; /* - * If the the challenge matches the response, - * the certificate public key, as well as the - * server public key, signatyre and identity are + * If the challenge matches the response, the + * server public key, signature and identity are * all verified at the same time. The server is * declared trusted, so we skip further - * certificate stages and move immediately to - * the cookie stage. + * certificate exchanges and move immediately to + * the cookie exchange. */ if ((rval = crypto_mv(ep, peer)) != XEVNT_OK) break; - peer->crypto |= CRYPTO_FLAG_VRFY | - CRYPTO_FLAG_PROV; + peer->crypto |= CRYPTO_FLAG_VRFY; peer->flash &= ~TEST8; - snprintf(statstr, NTP_MAXSTRLEN, "mv fs %u", - ntohl(ep->fstamp)); + snprintf(statstr, sizeof(statstr), "mv %s fs %u", + peer->issuer, ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); -#ifdef DEBUG - if (debug) - printf("crypto_recv: %s\n", statstr); -#endif + DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; - /* - * Cookie request in symmetric modes. Roll a random - * cookie and install in symmetric mode. Encrypt for the - * response, which is transmitted later. - */ - case CRYPTO_COOK: - - /* - * Discard the message if invalid or certificate - * trail not trusted. - */ - if (!(peer->crypto & CRYPTO_FLAG_VALID)) { - rval = XEVNT_ERR; - break; - } - if ((rval = crypto_verify(ep, NULL, peer)) != - XEVNT_OK) - break; - - /* - * Pass the extension field to the transmit - * side. If already agreed, walk away. - */ - fp = emalloc(len); - memcpy(fp, ep, len); - temp32 = CRYPTO_RESP; - fp->opcode |= htonl(temp32); - peer->cmmd = fp; - if (peer->crypto & CRYPTO_FLAG_AGREE) { - peer->flash &= ~TEST8; - break; - } - - /* - * Install cookie values and light the cookie - * bit. The transmit side will pick up and - * encrypt it for the response. - */ - key_expire(peer); - peer->cookval.tstamp = ep->tstamp; - peer->cookval.fstamp = ep->fstamp; - RAND_bytes((u_char *)&peer->pcookie, 4); - peer->crypto &= ~CRYPTO_FLAG_AUTO; - peer->crypto |= CRYPTO_FLAG_AGREE; - peer->flash &= ~TEST8; - snprintf(statstr, NTP_MAXSTRLEN, "cook %x ts %u fs %u", - peer->pcookie, ntohl(ep->tstamp), - ntohl(ep->fstamp)); - record_crypto_stats(&peer->srcadr, statstr); -#ifdef DEBUG - if (debug) - printf("crypto_recv: %s\n", statstr); -#endif - break; /* * Cookie response in client and symmetric modes. If the @@ -854,14 +789,10 @@ crypto_recv( case CRYPTO_COOK | CRYPTO_RESP: /* - * Discard the message if invalid or identity - * not confirmed or signature not verified with - * respect to the cookie values. + * Discard the message if invalid or signature + * not verified with respect to the cookie + * values. */ - if (!(peer->crypto & CRYPTO_FLAG_VRFY)) { - rval = XEVNT_ERR; - break; - } if ((rval = crypto_verify(ep, &peer->cookval, peer)) != XEVNT_OK) break; @@ -870,13 +801,14 @@ crypto_recv( * Decrypt the cookie, hunting all the time for * errors. */ - if (vallen == (u_int) EVP_PKEY_size(host_pkey)) { + if (vallen == (u_int)EVP_PKEY_size(host_pkey)) { u_int32 *cookiebuf = malloc( - RSA_size(host_pkey->pkey.rsa)); - if (cookiebuf == NULL) { + RSA_size(host_pkey->pkey.rsa)); + if (!cookiebuf) { rval = XEVNT_CKY; break; } + if (RSA_private_decrypt(vallen, (u_char *)ep->pkt, (u_char *)cookiebuf, @@ -900,27 +832,18 @@ crypto_recv( * are done here. */ key_expire(peer); - peer->cookval.tstamp = ep->tstamp; - peer->cookval.fstamp = ep->fstamp; - if (peer->crypto & CRYPTO_FLAG_AGREE) - peer->pcookie ^= cookie; + if (hismode == MODE_ACTIVE || hismode == + MODE_PASSIVE) + peer->pcookie = peer->hcookie ^ cookie; else peer->pcookie = cookie; - if (peer->hmode == MODE_CLIENT && - !(peer->cast_flags & MDF_BCLNT)) - peer->crypto |= CRYPTO_FLAG_AUTO; - else - peer->crypto &= ~CRYPTO_FLAG_AUTO; - peer->crypto |= CRYPTO_FLAG_AGREE; + peer->crypto |= CRYPTO_FLAG_COOK; peer->flash &= ~TEST8; - snprintf(statstr, NTP_MAXSTRLEN, "cook %x ts %u fs %u", - peer->pcookie, ntohl(ep->tstamp), - ntohl(ep->fstamp)); + snprintf(statstr, sizeof(statstr), + "cook %x ts %u fs %u", peer->pcookie, + ntohl(ep->tstamp), ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); -#ifdef DEBUG - if (debug) - printf("crypto_recv: %s\n", statstr); -#endif + DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* @@ -936,22 +859,32 @@ crypto_recv( case CRYPTO_AUTO | CRYPTO_RESP: /* - * Discard the message if invalid or identity - * not confirmed or signature not verified with - * respect to the receive autokey values. + * Discard the message if invalid or signature + * not verified with respect to the receive + * autokey values. */ - if (!(peer->crypto & CRYPTO_FLAG_VRFY)) { - rval = XEVNT_ERR; - break; - } if ((rval = crypto_verify(ep, &peer->recval, - peer)) != XEVNT_OK) + peer)) != XEVNT_OK) + break; + + /* + * Discard the message if a broadcast client and + * the association ID does not match. This might + * happen if a broacast server restarts the + * protocol. A protocol restart will occur at + * the next ASSOC message. + */ + if ((peer->cast_flags & MDF_BCLNT) && + peer->assoc != associd) break; /* * Install autokey values and light the * autokey bit. This is not hard. */ + if (ep->tstamp == 0) + break; + if (peer->recval.ptr == NULL) peer->recval.ptr = emalloc(sizeof(struct autokey)); @@ -964,15 +897,12 @@ crypto_recv( peer->pkeyid = bp->key; peer->crypto |= CRYPTO_FLAG_AUTO; peer->flash &= ~TEST8; - snprintf(statstr, NTP_MAXSTRLEN, + snprintf(statstr, sizeof(statstr), "auto seq %d key %x ts %u fs %u", bp->seq, bp->key, ntohl(ep->tstamp), ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); -#ifdef DEBUG - if (debug) - printf("crypto_recv: %s\n", statstr); -#endif + DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* @@ -985,13 +915,8 @@ crypto_recv( case CRYPTO_SIGN | CRYPTO_RESP: /* - * Discard the message if invalid or not - * proventic. + * Discard the message if invalid. */ - if (!(peer->crypto & CRYPTO_FLAG_PROV)) { - rval = XEVNT_ERR; - break; - } if ((rval = crypto_verify(ep, NULL, peer)) != XEVNT_OK) break; @@ -1001,118 +926,74 @@ crypto_recv( * versions and link the newest version first on * the list. */ - if ((rval = cert_install(ep, peer)) != XEVNT_OK) + if ((xinfo = cert_install(ep, peer)) == NULL) { + rval = XEVNT_CRT; break; - + } peer->crypto |= CRYPTO_FLAG_SIGN; peer->flash &= ~TEST8; - temp32 = cinfo->nid; - snprintf(statstr, NTP_MAXSTRLEN, - "sign %s 0x%x %s (%u) fs %u", - cinfo->issuer, cinfo->flags, + temp32 = xinfo->nid; + snprintf(statstr, sizeof(statstr), + "sign %s %s 0x%x %s (%u) fs %u", + xinfo->subject, xinfo->issuer, xinfo->flags, OBJ_nid2ln(temp32), temp32, ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); -#ifdef DEBUG - if (debug) - printf("crypto_recv: %s\n", statstr); -#endif + DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* - * Install leapseconds table in symmetric modes. This - * table is proventicated to the NIST primary servers, - * either by copying the file containing the table from - * a NIST server to a trusted server or directly using - * this protocol. While the entire table is installed at - * the server, presently only the current TAI offset is - * provided via the kernel to other applications. + * Install leapseconds values. While the leapsecond + * values epoch, TAI offset and values expiration epoch + * are retained, only the current TAI offset is provided + * via the kernel to other applications. */ - case CRYPTO_TAI: - + case CRYPTO_LEAP | CRYPTO_RESP: /* - * Discard the message if invalid. + * Discard the message if invalid. We can't + * compare the value timestamps here, as they + * can be updated by different servers. */ - if ((rval = crypto_verify(ep, NULL, peer)) != - XEVNT_OK) + rval = crypto_verify(ep, NULL, peer); + if ((rval != XEVNT_OK ) || + (vallen != 3*sizeof(uint32_t)) ) break; - /* - * Pass the extension field to the transmit - * side. Continue below if a leapseconds table - * accompanies the message. - */ - fp = emalloc(len); - memcpy(fp, ep, len); - temp32 = CRYPTO_RESP; - fp->opcode |= htonl(temp32); - peer->cmmd = fp; - if (len <= VALUE_LEN) { - peer->flash &= ~TEST8; - break; - } - /* fall through */ - - case CRYPTO_TAI | CRYPTO_RESP: - - /* - * If this is a response, discard the message if - * signature not verified with respect to the - * leapsecond table values. + /* Check if we can update the basic TAI offset + * for our current leap frame. This is a hack + * and ignores the time stamps in the autokey + * message. */ - if (peer->cmmd == NULL) { - if ((rval = crypto_verify(ep, - &peer->tai_leap, peer)) != XEVNT_OK) - break; - } - - /* - * Initialize peer variables with latest update. - */ - peer->tai_leap.tstamp = ep->tstamp; - peer->tai_leap.fstamp = ep->fstamp; - peer->tai_leap.vallen = ep->vallen; - - /* - * Install the new table if there is no stored - * table or the new table is more recent than - * the stored table. Since a filestamp may have - * changed, recompute the signatures. - */ - if (ntohl(peer->tai_leap.fstamp) > - ntohl(tai_leap.fstamp)) { - tai_leap.fstamp = ep->fstamp; - tai_leap.vallen = ep->vallen; - if (tai_leap.ptr != NULL) - free(tai_leap.ptr); - tai_leap.ptr = emalloc(vallen); - memcpy(tai_leap.ptr, ep->pkt, vallen); - crypto_update(); - } - crypto_flags |= CRYPTO_FLAG_TAI; + if (sys_leap != LEAP_NOTINSYNC) + leapsec_autokey_tai(ntohl(ep->pkt[0]), + rbufp->recv_time.l_ui, NULL); + tai_leap.tstamp = ep->tstamp; + tai_leap.fstamp = ep->fstamp; + crypto_update(); + mprintf_event(EVNT_TAI, peer, + "%d seconds", ntohl(ep->pkt[0])); peer->crypto |= CRYPTO_FLAG_LEAP; peer->flash &= ~TEST8; - snprintf(statstr, NTP_MAXSTRLEN, - "leap %u ts %u fs %u", vallen, - ntohl(ep->tstamp), ntohl(ep->fstamp)); + snprintf(statstr, sizeof(statstr), + "leap TAI offset %d at %u expire %u fs %u", + ntohl(ep->pkt[0]), ntohl(ep->pkt[1]), + ntohl(ep->pkt[2]), ntohl(ep->fstamp)); record_crypto_stats(&peer->srcadr, statstr); -#ifdef DEBUG - if (debug) - printf("crypto_recv: %s\n", statstr); -#endif + DPRINTF(1, ("crypto_recv: %s\n", statstr)); break; /* * We come here in symmetric modes for miscellaneous * commands that have value fields but are processed on * the transmit side. All we need do here is check for - * valid field length. Remaining checks are below and on - * the transmit side. + * valid field length. Note that ASSOC is handled + * separately. */ case CRYPTO_CERT: case CRYPTO_IFF: case CRYPTO_GQ: case CRYPTO_MV: + case CRYPTO_COOK: case CRYPTO_SIGN: if (len < VALUE_LEN) { rval = XEVNT_LEN; @@ -1121,49 +1002,36 @@ crypto_recv( /* fall through */ /* - * We come here for miscellaneous requests and unknown - * requests and responses. If an unknown response or - * error, forget it. If a request, save the extension - * field for later. Unknown requests will be caught on - * the transmit side. + * We come here in symmetric modes for requests + * requiring a response (above plus AUTO and LEAP) and + * for responses. If a request, save the extension field + * for later; invalid requests will be caught on the + * transmit side. If an error or invalid response, + * declare a protocol error. */ default: if (code & (CRYPTO_RESP | CRYPTO_ERROR)) { rval = XEVNT_ERR; - } else if ((rval = crypto_verify(ep, NULL, - peer)) == XEVNT_OK) { + } else if (peer->cmmd == NULL) { fp = emalloc(len); memcpy(fp, ep, len); - temp32 = CRYPTO_RESP; - fp->opcode |= htonl(temp32); peer->cmmd = fp; } } /* - * We don't log length/format/timestamp errors and - * duplicates, which are log clogging vulnerabilities. * The first error found terminates the extension field - * scan and we return the laundry to the caller. A - * length/format/timestamp error on transmit is - * cheerfully ignored, as the message is not sent. + * scan and we return the laundry to the caller. */ - if (rval > XEVNT_TSP) { - snprintf(statstr, NTP_MAXSTRLEN, - "error %x opcode %x ts %u fs %u", rval, - code, tstamp, fstamp); + if (rval != XEVNT_OK) { + snprintf(statstr, sizeof(statstr), + "%04x %d %02x %s", htonl(ep->opcode), + associd, rval, eventstr(rval)); record_crypto_stats(&peer->srcadr, statstr); - report_event(rval, peer); -#ifdef DEBUG - if (debug) - printf("crypto_recv: %s\n", statstr); -#endif - break; - - } else if (rval > XEVNT_OK && (code & CRYPTO_RESP)) { - rval = XEVNT_OK; + DPRINTF(1, ("crypto_recv: %s\n", statstr)); + return (rval); } - authlen += len; + authlen += (len + 3) / 4 * 4; } return (rval); } @@ -1177,30 +1045,39 @@ crypto_recv( * autokey information, in which case the caller has to provide the * association ID to match the association. * - * Returns length of extension field. + * Side effect: update the packet offset. + * + * Errors + * XEVNT_OK success + * XEVNT_CRT bad or missing certificate + * XEVNT_ERR protocol error + * XEVNT_LEN bad field format or length + * XEVNT_PER host certificate expired */ int crypto_xmit( + struct peer *peer, /* peer structure pointer */ struct pkt *xpkt, /* transmit packet pointer */ - struct sockaddr_storage *srcadr_sin, /* active runway */ + struct recvbuf *rbufp, /* receive buffer pointer */ int start, /* offset to extension field */ struct exten *ep, /* extension pointer */ keyid_t cookie /* session cookie */ ) { + struct exten *fp; /* extension pointers */ + struct cert_info *cp, *xp, *yp; /* cert info/value pointer */ + sockaddr_u *srcadr_sin; /* source address */ u_int32 *pkt; /* packet pointer */ - struct peer *peer; /* peer structure pointer */ u_int opcode; /* extension field opcode */ - struct exten *fp; /* extension pointers */ - struct cert_info *cp, *xp; /* certificate info/value pointer */ char certname[MAXHOSTNAME + 1]; /* subject name buffer */ char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */ tstamp_t tstamp; + struct calendar tscal; u_int vallen; - u_int len; struct value vtemp; associd_t associd; int rval; + int len; keyid_t tcookie; /* @@ -1211,9 +1088,17 @@ crypto_xmit( pkt = (u_int32 *)xpkt + start / 4; fp = (struct exten *)pkt; opcode = ntohl(ep->opcode); + if (peer != NULL) { + srcadr_sin = &peer->srcadr; + if (!(opcode & CRYPTO_RESP)) + peer->opcode = ep->opcode; + } else { + srcadr_sin = &rbufp->recv_srcadr; + } associd = (associd_t) ntohl(ep->associd); - fp->associd = htonl(associd); len = 8; + fp->opcode = htonl((opcode & 0xffff0000) | len); + fp->associd = ep->associd; rval = XEVNT_OK; tstamp = crypto_time(); switch (opcode & 0xffff0000) { @@ -1223,16 +1108,12 @@ crypto_xmit( * host name. Note, this message is not signed and the filestamp * contains only the status word. */ + case CRYPTO_ASSOC: case CRYPTO_ASSOC | CRYPTO_RESP: - len += crypto_send(fp, &hostval); + len = crypto_send(fp, &hostval, start); fp->fstamp = htonl(crypto_flags); break; - case CRYPTO_ASSOC: - len += crypto_send(fp, &hostval); - fp->fstamp = htonl(crypto_flags | ident_scheme); - break; - /* * Send certificate request. Use the values from the extension * field. @@ -1243,89 +1124,99 @@ crypto_xmit( vtemp.fstamp = ep->fstamp; vtemp.vallen = ep->vallen; vtemp.ptr = (u_char *)ep->pkt; - len += crypto_send(fp, &vtemp); + len = crypto_send(fp, &vtemp, start); break; /* - * Send certificate response or sign request. Use the values - * from the certificate cache. If the request contains no - * subject name, assume the name of this host. This is for - * backwards compatibility. Private certificates are never sent. + * Send sign request. Use the host certificate, which is self- + * signed and may or may not be trusted. */ case CRYPTO_SIGN: + (void)ntpcal_ntp_to_date(&tscal, tstamp, NULL); + if ((calcomp(&tscal, &(cert_host->first)) < 0) + || (calcomp(&tscal, &(cert_host->last)) > 0)) + rval = XEVNT_PER; + else + len = crypto_send(fp, &cert_host->cert, start); + break; + + /* + * Send certificate response. Use the name in the extension + * field to find the certificate in the cache. If the request + * contains no subject name, assume the name of this host. This + * is for backwards compatibility. Private certificates are + * never sent. + * + * There may be several certificates matching the request. First + * choice is a self-signed trusted certificate; second choice is + * any certificate signed by another host. There is no third + * choice. + */ case CRYPTO_CERT | CRYPTO_RESP: - vallen = ntohl(ep->vallen); - if (vallen == 8) { - strcpy(certname, sys_hostname); - } else if (vallen == 0 || vallen > MAXHOSTNAME || + vallen = ntohl(ep->vallen); /* Must be <64k */ + if (vallen == 0 || vallen > MAXHOSTNAME || len - VALUE_LEN < vallen) { rval = XEVNT_LEN; break; - - } else { - memcpy(certname, ep->pkt, vallen); - certname[vallen] = '\0'; } /* - * Find all certificates with matching subject. If a - * self-signed, trusted certificate is found, use that. - * If not, use the first one with matching subject. A - * private certificate is never divulged or signed. + * Find all public valid certificates with matching + * subject. If a self-signed, trusted certificate is + * found, use that certificate. If not, use the last non + * self-signed certificate. */ - xp = NULL; + memcpy(certname, ep->pkt, vallen); + certname[vallen] = '\0'; + xp = yp = NULL; for (cp = cinfo; cp != NULL; cp = cp->link) { - if (cp->flags & CERT_PRIV) + if (cp->flags & (CERT_PRIV | CERT_ERROR)) continue; - if (strcmp(certname, cp->subject) == 0) { - if (xp == NULL) - xp = cp; - if (strcmp(certname, cp->issuer) == - 0 && cp->flags & CERT_TRUST) { - xp = cp; - break; - } - } + if (strcmp(certname, cp->subject) != 0) + continue; + + if (strcmp(certname, cp->issuer) != 0) + yp = cp; + else if (cp ->flags & CERT_TRUST) + xp = cp; + continue; } /* - * Be careful who you trust. If not yet synchronized, - * give back an empty response. If certificate not found - * or beyond the lifetime, return an error. This is to - * avoid a bad dude trying to get an expired certificate - * re-signed. Otherwise, send it. + * Be careful who you trust. If the certificate is not + * found, return an empty response. Note that we dont + * enforce lifetimes here. * - * Note the timestamp and filestamp are taken from the + * The timestamp and filestamp are taken from the * certificate value structure. For all certificates the * timestamp is the latest signature update time. For * host and imported certificates the filestamp is the * creation epoch. For signed certificates the filestamp * is the creation epoch of the trusted certificate at - * the base of the certificate trail. In principle, this + * the root of the certificate trail. In principle, this * allows strong checking for signature masquerade. */ + if (xp == NULL) + xp = yp; + if (xp == NULL) + break; + if (tstamp == 0) break; - if (xp == NULL) - rval = XEVNT_CRT; - else if (tstamp < xp->first || tstamp > xp->last) - rval = XEVNT_SRV; - else - len += crypto_send(fp, &xp->cert); + len = crypto_send(fp, &xp->cert, start); break; /* * Send challenge in Schnorr (IFF) identity scheme. */ case CRYPTO_IFF: - if ((peer = findpeerbyassoc(ep->pkt[0])) == NULL) { - rval = XEVNT_ERR; - break; - } + if (peer == NULL) + break; /* hack attack */ + if ((rval = crypto_alice(peer, &vtemp)) == XEVNT_OK) { - len += crypto_send(fp, &vtemp); + len = crypto_send(fp, &vtemp, start); value_free(&vtemp); } break; @@ -1335,7 +1226,7 @@ crypto_xmit( */ case CRYPTO_IFF | CRYPTO_RESP: if ((rval = crypto_bob(ep, &vtemp)) == XEVNT_OK) { - len += crypto_send(fp, &vtemp); + len = crypto_send(fp, &vtemp, start); value_free(&vtemp); } break; @@ -1344,12 +1235,11 @@ crypto_xmit( * Send challenge in Guillou-Quisquater (GQ) identity scheme. */ case CRYPTO_GQ: - if ((peer = findpeerbyassoc(ep->pkt[0])) == NULL) { - rval = XEVNT_ERR; - break; - } + if (peer == NULL) + break; /* hack attack */ + if ((rval = crypto_alice2(peer, &vtemp)) == XEVNT_OK) { - len += crypto_send(fp, &vtemp); + len = crypto_send(fp, &vtemp, start); value_free(&vtemp); } break; @@ -1359,7 +1249,7 @@ crypto_xmit( */ case CRYPTO_GQ | CRYPTO_RESP: if ((rval = crypto_bob2(ep, &vtemp)) == XEVNT_OK) { - len += crypto_send(fp, &vtemp); + len = crypto_send(fp, &vtemp, start); value_free(&vtemp); } break; @@ -1368,12 +1258,11 @@ crypto_xmit( * Send challenge in MV identity scheme. */ case CRYPTO_MV: - if ((peer = findpeerbyassoc(ep->pkt[0])) == NULL) { - rval = XEVNT_ERR; - break; - } + if (peer == NULL) + break; /* hack attack */ + if ((rval = crypto_alice3(peer, &vtemp)) == XEVNT_OK) { - len += crypto_send(fp, &vtemp); + len = crypto_send(fp, &vtemp, start); value_free(&vtemp); } break; @@ -1383,7 +1272,7 @@ crypto_xmit( */ case CRYPTO_MV | CRYPTO_RESP: if ((rval = crypto_bob3(ep, &vtemp)) == XEVNT_OK) { - len += crypto_send(fp, &vtemp); + len = crypto_send(fp, &vtemp, start); value_free(&vtemp); } break; @@ -1397,9 +1286,10 @@ crypto_xmit( * invalid or contains an unverified signature. */ case CRYPTO_SIGN | CRYPTO_RESP: - if ((rval = cert_sign(ep, &vtemp)) == XEVNT_OK) - len += crypto_send(fp, &vtemp); - value_free(&vtemp); + if ((rval = cert_sign(ep, &vtemp)) == XEVNT_OK) { + len = crypto_send(fp, &vtemp, start); + value_free(&vtemp); + } break; /* @@ -1407,7 +1297,7 @@ crypto_xmit( * key. */ case CRYPTO_COOK: - len += crypto_send(fp, &pubkey); + len = crypto_send(fp, &pubkey, start); break; /* @@ -1422,18 +1312,13 @@ crypto_xmit( rval = XEVNT_LEN; break; } - if (PKT_MODE(xpkt->li_vn_mode) == MODE_SERVER) { + if (peer == NULL) tcookie = cookie; - } else { - if ((peer = findpeerbyassoc(associd)) == NULL) { - rval = XEVNT_ERR; - break; - } - tcookie = peer->pcookie; - } + else + tcookie = peer->hcookie; if ((rval = crypto_encrypt((const u_char *)ep->pkt, vallen, &tcookie, &vtemp)) == XEVNT_OK) { - len += crypto_send(fp, &vtemp); + len = crypto_send(fp, &vtemp, start); value_free(&vtemp); } break; @@ -1446,28 +1331,28 @@ crypto_xmit( * old message, in which case light the error bit. */ case CRYPTO_AUTO | CRYPTO_RESP: - if ((peer = findpeerbyassoc(associd)) == NULL) { - rval = XEVNT_ERR; - break; + if (peer == NULL) { + if ((peer = findpeerbyassoc(associd)) == NULL) { + rval = XEVNT_ERR; + break; + } } peer->flags &= ~FLAG_ASSOC; - len += crypto_send(fp, &peer->sndval); + len = crypto_send(fp, &peer->sndval, start); break; /* - * Send leapseconds table and signature. Use the values from the - * tai structure. If no table has been loaded, just send an + * Send leapseconds values and signature. Use the values from + * the tai structure. If no table has been loaded, just send an * empty request. */ - case CRYPTO_TAI: - case CRYPTO_TAI | CRYPTO_RESP: - if (crypto_flags & CRYPTO_FLAG_TAI) - len += crypto_send(fp, &tai_leap); + case CRYPTO_LEAP | CRYPTO_RESP: + len = crypto_send(fp, &tai_leap, start); break; /* - * Default - Fall through for requests; for unknown responses, - * flag as error. + * Default - Send a valid command for unknown requests; send + * an error response for unknown resonses. */ default: if (opcode & CRYPTO_RESP) @@ -1479,47 +1364,37 @@ crypto_xmit( * puppy; if a response, return so the sender can flame, too. */ if (rval != XEVNT_OK) { - opcode |= CRYPTO_ERROR; - snprintf(statstr, NTP_MAXSTRLEN, - "error %x opcode %x", rval, opcode); + u_int32 uint32; + + uint32 = CRYPTO_ERROR; + opcode |= uint32; + fp->opcode |= htonl(uint32); + snprintf(statstr, sizeof(statstr), + "%04x %d %02x %s", opcode, associd, rval, + eventstr(rval)); record_crypto_stats(srcadr_sin, statstr); - report_event(rval, NULL); -#ifdef DEBUG - if (debug) - printf("crypto_xmit: %s\n", statstr); -#endif + DPRINTF(1, ("crypto_xmit: %s\n", statstr)); if (!(opcode & CRYPTO_RESP)) return (0); } - - /* - * Round up the field length to a multiple of 8 bytes and save - * the request code and length. - */ - len = ((len + 7) / 8) * 8; - fp->opcode = htonl((opcode & 0xffff0000) | len); -#ifdef DEBUG - if (debug) - printf( - "crypto_xmit: flags 0x%x ext offset %d len %u code 0x%x assocID %d\n", - crypto_flags, start, len, opcode >> 16, associd); -#endif + DPRINTF(1, ("crypto_xmit: flags 0x%x offset %d len %d code 0x%x associd %d\n", + crypto_flags, start, len, opcode >> 16, associd)); return (len); } /* - * crypto_verify - parse and verify the extension field and value + * crypto_verify - verify the extension field value and signature * * Returns * XEVNT_OK success - * XEVNT_LEN bad field format or length - * XEVNT_TSP bad timestamp + * XEVNT_ERR protocol error * XEVNT_FSP bad filestamp + * XEVNT_LEN bad field format or length * XEVNT_PUB bad or missing public key * XEVNT_SGL bad signature length * XEVNT_SIG signature not verified - * XEVNT_ERR protocol error + * XEVNT_TSP bad timestamp */ static int crypto_verify( @@ -1538,41 +1413,47 @@ crypto_verify( int i; /* - * We require valid opcode and field lengths, timestamp, - * filestamp, public key, digest, signature length and - * signature, where relevant. Note that preliminary length - * checks are done in the main loop. + * We are extremely parannoyed. We require valid opcode, length, + * association ID, timestamp, filestamp, public key, digest, + * signature length and signature, where relevant. Note that + * preliminary length checks are done in the main loop. */ len = ntohl(ep->opcode) & 0x0000ffff; opcode = ntohl(ep->opcode) & 0xffff0000; /* - * Check for valid operation code and protocol. The opcode must - * not have the error bit set. If a response, it must have a - * value header. If a request and does not contain a value - * header, no need for further checking. + * Check for valid value header, association ID and extension + * field length. Remember, it is not an error to receive an + * unsolicited response; however, the response ID must match + * the association ID. */ if (opcode & CRYPTO_ERROR) return (XEVNT_ERR); - if (opcode & CRYPTO_RESP) { - if (len < VALUE_LEN) - return (XEVNT_LEN); + if (len < VALUE_LEN) + return (XEVNT_LEN); + + if (opcode == (CRYPTO_AUTO | CRYPTO_RESP) && (peer->pmode == + MODE_BROADCAST || (peer->cast_flags & MDF_BCLNT))) { + if (ntohl(ep->associd) != peer->assoc) + return (XEVNT_ERR); } else { - if (len < VALUE_LEN) - return (XEVNT_OK); + if (ntohl(ep->associd) != peer->associd) + return (XEVNT_ERR); } /* - * We have a value header. Check for valid field lengths. The - * field length must be long enough to contain the value header, - * value and signature. Note both the value and signature fields - * are rounded up to the next word. + * We have a valid value header. Check for valid value and + * signature field lengths. The extension field length must be + * long enough to contain the value header, value and signature. + * Note both the value and signature field lengths are rounded + * up to the next word (4 octets). */ vallen = ntohl(ep->vallen); if ( vallen == 0 || vallen > MAX_VALLEN) return (XEVNT_LEN); + i = (vallen + 3) / 4; siglen = ntohl(ep->pkt[i++]); if ( siglen > MAX_VALLEN @@ -1582,32 +1463,16 @@ crypto_verify( return (XEVNT_LEN); /* - * Punt if this is a response with no data. Punt if this is a - * request and a previous response is pending. - */ - if (opcode & CRYPTO_RESP) { - if (vallen == 0) - return (XEVNT_LEN); - } else { - if (peer->cmmd != NULL) - return (XEVNT_LEN); - } - - /* * Check for valid timestamp and filestamp. If the timestamp is * zero, the sender is not synchronized and signatures are - * disregarded. If not, the timestamp must not precede the + * not possible. If nonzero the timestamp must not precede the * filestamp. The timestamp and filestamp must not precede the - * corresponding values in the value structure, if present. Once - * the autokey values have been installed, the timestamp must - * always be later than the corresponding value in the value - * structure. Duplicate timestamps are illegal once the cookie - * has been validated. - */ + * corresponding values in the value structure, if present. + */ tstamp = ntohl(ep->tstamp); fstamp = ntohl(ep->fstamp); if (tstamp == 0) - return (XEVNT_OK); + return (XEVNT_TSP); if (tstamp < fstamp) return (XEVNT_TSP); @@ -1615,15 +1480,24 @@ crypto_verify( if (vp != NULL) { tstamp1 = ntohl(vp->tstamp); fstamp1 = ntohl(vp->fstamp); - if ((tstamp < tstamp1 || (tstamp == tstamp1 && - (peer->crypto & CRYPTO_FLAG_AUTO)))) - return (XEVNT_TSP); + if (tstamp1 != 0 && fstamp1 != 0) { + if (tstamp < tstamp1) + return (XEVNT_TSP); - if ((tstamp < fstamp1 || fstamp < fstamp1)) - return (XEVNT_FSP); + if ((tstamp < fstamp1 || fstamp < fstamp1)) + return (XEVNT_FSP); + } } /* + * At the time the certificate message is validated, the public + * key in the message is not available. Thus, don't try to + * verify the signature. + */ + if (opcode == (CRYPTO_CERT | CRYPTO_RESP)) + return (XEVNT_OK); + + /* * Check for valid signature length, public key and digest * algorithm. */ @@ -1632,7 +1506,7 @@ crypto_verify( else pkey = peer->pkey; if (siglen == 0 || pkey == NULL || peer->digest == NULL) - return (XEVNT_OK); + return (XEVNT_ERR); if (siglen != (u_int)EVP_PKEY_size(pkey)) return (XEVNT_SGL); @@ -1640,20 +1514,17 @@ crypto_verify( /* * Darn, I thought we would never get here. Verify the * signature. If the identity exchange is verified, light the - * proventic bit. If no client identity scheme is specified, - * avoid doing the sign exchange. + * proventic bit. What a relief. */ EVP_VerifyInit(&ctx, peer->digest); /* XXX: the "+ 12" needs to be at least documented... */ EVP_VerifyUpdate(&ctx, (u_char *)&ep->tstamp, vallen + 12); - if (EVP_VerifyFinal(&ctx, (u_char *)&ep->pkt[i], siglen, pkey) <= 0) + if (EVP_VerifyFinal(&ctx, (u_char *)&ep->pkt[i], siglen, + pkey) <= 0) return (XEVNT_SIG); - if (peer->crypto & CRYPTO_FLAG_VRFY) { + if (peer->crypto & CRYPTO_FLAG_VRFY) peer->crypto |= CRYPTO_FLAG_PROV; - if (!(crypto_flags & CRYPTO_FLAG_MASK)) - peer->crypto |= CRYPTO_FLAG_SIGN; - } return (XEVNT_OK); } @@ -1664,9 +1535,8 @@ crypto_verify( * * Returns: * XEVNT_OK success - * XEVNT_PUB bad or missing public key * XEVNT_CKY bad or missing cookie - * XEVNT_PER host certificate expired + * XEVNT_PUB bad or missing public key */ static int crypto_encrypt( @@ -1680,13 +1550,14 @@ crypto_encrypt( EVP_MD_CTX ctx; /* signature context */ tstamp_t tstamp; /* NTP timestamp */ u_int32 temp32; + u_char *puch; /* * Extract the public key from the request. */ pkey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &ptr, vallen); if (pkey == NULL) { - msyslog(LOG_ERR, "crypto_encrypt %s\n", + msyslog(LOG_ERR, "crypto_encrypt: %s", ERR_error_string(ERR_get_error(), NULL)); return (XEVNT_PUB); } @@ -1694,35 +1565,35 @@ crypto_encrypt( /* * Encrypt the cookie, encode in ASN.1 and sign. */ - tstamp = crypto_time(); memset(vp, 0, sizeof(struct value)); + tstamp = crypto_time(); vp->tstamp = htonl(tstamp); vp->fstamp = hostval.tstamp; vallen = EVP_PKEY_size(pkey); vp->vallen = htonl(vallen); vp->ptr = emalloc(vallen); + puch = vp->ptr; temp32 = htonl(*cookie); - if (!RSA_public_encrypt(4, (u_char *)&temp32, vp->ptr, - pkey->pkey.rsa, RSA_PKCS1_OAEP_PADDING)) { - msyslog(LOG_ERR, "crypto_encrypt %s\n", + if (RSA_public_encrypt(4, (u_char *)&temp32, puch, + pkey->pkey.rsa, RSA_PKCS1_OAEP_PADDING) <= 0) { + msyslog(LOG_ERR, "crypto_encrypt: %s", ERR_error_string(ERR_get_error(), NULL)); + free(vp->ptr); EVP_PKEY_free(pkey); return (XEVNT_CKY); } EVP_PKEY_free(pkey); - vp->siglen = 0; if (tstamp == 0) return (XEVNT_OK); - if (tstamp < cinfo->first || tstamp > cinfo->last) - return (XEVNT_PER); - vp->sig = emalloc(sign_siglen); EVP_SignInit(&ctx, sign_digest); EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12); EVP_SignUpdate(&ctx, vp->ptr, vallen); - if (EVP_SignFinal(&ctx, vp->sig, &vallen, sign_pkey)) - vp->siglen = htonl(sign_siglen); + if (EVP_SignFinal(&ctx, vp->sig, &vallen, sign_pkey)) { + NTP_INSIST(vallen <= sign_siglen); + vp->siglen = htonl(vallen); + } return (XEVNT_OK); } @@ -1732,71 +1603,54 @@ crypto_encrypt( * * This routine determines which identity scheme is in use and * constructs an extension field for that scheme. + * + * Returns + * CRYTPO_IFF IFF scheme + * CRYPTO_GQ GQ scheme + * CRYPTO_MV MV scheme + * CRYPTO_NULL no available scheme */ u_int crypto_ident( struct peer *peer /* peer structure pointer */ ) { - char filename[MAXFILENAME + 1]; + char filename[MAXFILENAME]; + const char * scheme_name; + u_int scheme_id; /* - * If the server identity has already been verified, no further - * action is necessary. Otherwise, try to load the identity file - * of the certificate issuer. If the issuer file is not found, - * try the host file. If nothing found, declare a cryptobust. - * Note we can't get here unless the trusted certificate has - * been found and the CRYPTO_FLAG_VALID bit is set, so the - * certificate issuer is valid. + * We come here after the group trusted host has been found; its + * name defines the group name. Search the key cache for all + * keys matching the same group name in order IFF, GQ and MV. + * Use the first one available. */ - if (peer->ident_pkey != NULL) - EVP_PKEY_free(peer->ident_pkey); - if (peer->crypto & CRYPTO_FLAG_GQ) { - snprintf(filename, MAXFILENAME, "ntpkey_gq_%s", - peer->issuer); - peer->ident_pkey = crypto_key(filename, &peer->fstamp); - if (peer->ident_pkey != NULL) - return (CRYPTO_GQ); - - snprintf(filename, MAXFILENAME, "ntpkey_gq_%s", - sys_hostname); - peer->ident_pkey = crypto_key(filename, &peer->fstamp); - if (peer->ident_pkey != NULL) - return (CRYPTO_GQ); - } + scheme_name = NULL; if (peer->crypto & CRYPTO_FLAG_IFF) { - snprintf(filename, MAXFILENAME, "ntpkey_iff_%s", - peer->issuer); - peer->ident_pkey = crypto_key(filename, &peer->fstamp); + scheme_name = "iff"; + scheme_id = CRYPTO_IFF; + } else if (peer->crypto & CRYPTO_FLAG_GQ) { + scheme_name = "gq"; + scheme_id = CRYPTO_GQ; + } else if (peer->crypto & CRYPTO_FLAG_MV) { + scheme_name = "mv"; + scheme_id = CRYPTO_MV; + } + + if (scheme_name != NULL) { + snprintf(filename, sizeof(filename), "ntpkey_%spar_%s", + scheme_name, peer->ident); + peer->ident_pkey = crypto_key(filename, NULL, + &peer->srcadr); if (peer->ident_pkey != NULL) - return (CRYPTO_IFF); - - snprintf(filename, MAXFILENAME, "ntpkey_iff_%s", - sys_hostname); - peer->ident_pkey = crypto_key(filename, &peer->fstamp); - if (peer->ident_pkey != NULL) - return (CRYPTO_IFF); + return scheme_id; } - if (peer->crypto & CRYPTO_FLAG_MV) { - snprintf(filename, MAXFILENAME, "ntpkey_mv_%s", - peer->issuer); - peer->ident_pkey = crypto_key(filename, &peer->fstamp); - if (peer->ident_pkey != NULL) - return (CRYPTO_MV); - snprintf(filename, MAXFILENAME, "ntpkey_mv_%s", - sys_hostname); - peer->ident_pkey = crypto_key(filename, &peer->fstamp); - if (peer->ident_pkey != NULL) - return (CRYPTO_MV); - } + msyslog(LOG_NOTICE, + "crypto_ident: no identity parameters found for group %s", + peer->ident); - /* - * No compatible identity scheme is available. Life is hard. - */ - msyslog(LOG_INFO, - "crypto_ident: no compatible identity scheme found"); - return (0); + return CRYPTO_NULL; } @@ -1808,7 +1662,7 @@ crypto_ident( * extension field is created here, but freed after the crypto_xmit() * call in the protocol module. * - * Returns extension field pointer (no errors). + * Returns extension field pointer (no errors) * * XXX: opcode and len should really be 32-bit quantities and * we should make sure that str is not too big. @@ -1817,43 +1671,37 @@ struct exten * crypto_args( struct peer *peer, /* peer structure pointer */ u_int opcode, /* operation code */ + associd_t associd, /* association ID */ char *str /* argument string */ ) { tstamp_t tstamp; /* NTP timestamp */ struct exten *ep; /* extension field pointer */ u_int len; /* extension field length */ - size_t slen; + size_t slen = 0; tstamp = crypto_time(); len = sizeof(struct exten); if (str != NULL) { slen = strlen(str); + INSIST(slen < MAX_VALLEN); len += slen; } - ep = emalloc(len); - memset(ep, 0, len); + ep = emalloc_zero(len); if (opcode == 0) return (ep); - ep->opcode = htonl(opcode + len); + REQUIRE(0 == (len & ~0x0000ffff)); + REQUIRE(0 == (opcode & ~0xffff0000)); - /* - * If a response, send our ID; if a request, send the - * responder's ID. - */ - if (opcode & CRYPTO_RESP) - ep->associd = htonl(peer->associd); - else - ep->associd = htonl(peer->assoc); + ep->opcode = htonl(opcode + len); + ep->associd = htonl(associd); ep->tstamp = htonl(tstamp); ep->fstamp = hostval.tstamp; ep->vallen = 0; if (str != NULL) { ep->vallen = htonl(slen); memcpy((char *)ep->pkt, str, slen); - } else { - ep->pkt[0] = peer->associd; } return (ep); } @@ -1862,44 +1710,71 @@ crypto_args( /* * crypto_send - construct extension field from value components * - * Returns extension field length. Note: it is not polite to send a - * nonempty signature with zero timestamp or a nonzero timestamp with - * empty signature, but these rules are not enforced here. + * The value and signature fields are zero-padded to a word boundary. + * Note: it is not polite to send a nonempty signature with zero + * timestamp or a nonzero timestamp with an empty signature, but those + * rules are not enforced here. * * XXX This code won't work on a box with 16-bit ints. */ -u_int +int crypto_send( struct exten *ep, /* extension field pointer */ - struct value *vp /* value pointer */ + struct value *vp, /* value pointer */ + int start /* buffer offset */ ) { - u_int len, temp32; - int i; + u_int len, vallen, siglen, opcode; + u_int i, j; /* - * Copy data. If the data field is empty or zero length, encode - * an empty value with length zero. + * Calculate extension field length and check for buffer + * overflow. Leave room for the MAC. + */ + len = 16; /* XXX Document! */ + vallen = ntohl(vp->vallen); + INSIST(vallen <= MAX_VALLEN); + len += ((vallen + 3) / 4 + 1) * 4; + siglen = ntohl(vp->siglen); + len += ((siglen + 3) / 4 + 1) * 4; + if (start + len > sizeof(struct pkt) - MAX_MAC_LEN) + return (0); + + /* + * Copy timestamps. */ ep->tstamp = vp->tstamp; ep->fstamp = vp->fstamp; ep->vallen = vp->vallen; - len = 12; - temp32 = ntohl(vp->vallen); - if (temp32 > 0 && vp->ptr != NULL) - memcpy(ep->pkt, vp->ptr, temp32); + + /* + * Copy value. If the data field is empty or zero length, + * encode an empty value with length zero. + */ + i = 0; + if (vallen > 0 && vp->ptr != NULL) { + j = vallen / 4; + if (j * 4 < vallen) + ep->pkt[i + j++] = 0; + memcpy(&ep->pkt[i], vp->ptr, vallen); + i += j; + } /* * Copy signature. If the signature field is empty or zero * length, encode an empty signature with length zero. */ - i = (temp32 + 3) / 4; - len += i * 4 + 4; ep->pkt[i++] = vp->siglen; - temp32 = ntohl(vp->siglen); - if (temp32 > 0 && vp->sig != NULL) - memcpy(&ep->pkt[i], vp->sig, temp32); - len += temp32; + if (siglen > 0 && vp->sig != NULL) { + j = siglen / 4; + if (j * 4 < siglen) + ep->pkt[i + j++] = 0; + memcpy(&ep->pkt[i], vp->sig, siglen); + i += j; + } + opcode = ntohl(ep->opcode); + ep->opcode = htonl((opcode & 0xffff0000) | len); + ENSURE(len <= MAX_VALLEN); return (len); } @@ -1914,12 +1789,11 @@ crypto_send( * hostval host name (not signed) * pubkey public key * cinfo certificate info/value list - * tai_leap leapseconds file + * tai_leap leap values * - * Filestamps are proventicated data, so this routine is run only when - * the host has been synchronized to a proventicated source. Thus, the - * timestamp is proventicated, too, and can be used to deflect - * clogging attacks and even cook breakfast. + * Filestamps are proventic data, so this routine runs only when the + * host is synchronized to a proventicated source. Thus, the timestamp + * is proventic and can be used to deflect clogging attacks. * * Returns void (no errors) */ @@ -1927,16 +1801,16 @@ void crypto_update(void) { EVP_MD_CTX ctx; /* message digest context */ - struct cert_info *cp, *cpn; /* certificate info/value */ + struct cert_info *cp; /* certificate info/value */ char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */ - tstamp_t tstamp; /* NTP timestamp */ + u_int32 *ptr; u_int len; + leap_result_t leap_data; - if ((tstamp = crypto_time()) == 0) + hostval.tstamp = htonl(crypto_time()); + if (hostval.tstamp == 0) return; - hostval.tstamp = htonl(tstamp); - /* * Sign public key and timestamps. The filestamp is derived from * the host key file extension from wherever the file was @@ -1950,8 +1824,10 @@ crypto_update(void) EVP_SignInit(&ctx, sign_digest); EVP_SignUpdate(&ctx, (u_char *)&pubkey, 12); EVP_SignUpdate(&ctx, pubkey.ptr, ntohl(pubkey.vallen)); - if (EVP_SignFinal(&ctx, pubkey.sig, &len, sign_pkey)) + if (EVP_SignFinal(&ctx, pubkey.sig, &len, sign_pkey)) { + NTP_INSIST(len <= sign_siglen); pubkey.siglen = htonl(len); + } } /* @@ -1960,8 +1836,7 @@ crypto_update(void) * was generated. Note we do not throw expired certificates * away; they may have signed younger ones. */ - for (cp = cinfo; cp != NULL; cp = cpn) { - cpn = cp->link; + for (cp = cinfo; cp != NULL; cp = cp->link) { cp->cert.tstamp = hostval.tstamp; cp->cert.siglen = 0; if (cp->cert.sig == NULL) @@ -1970,36 +1845,98 @@ crypto_update(void) EVP_SignUpdate(&ctx, (u_char *)&cp->cert, 12); EVP_SignUpdate(&ctx, cp->cert.ptr, ntohl(cp->cert.vallen)); - if (EVP_SignFinal(&ctx, cp->cert.sig, &len, sign_pkey)) + if (EVP_SignFinal(&ctx, cp->cert.sig, &len, sign_pkey)) { + NTP_INSIST(len <= sign_siglen); cp->cert.siglen = htonl(len); + } } /* - * Sign leapseconds table and timestamps. The filestamp is - * derived from the leapsecond file extension from wherever the - * file was generated. + * Sign leapseconds values and timestamps. Note it is not an + * error to return null values. */ - if (tai_leap.vallen != 0) { - tai_leap.tstamp = hostval.tstamp; - tai_leap.siglen = 0; - if (tai_leap.sig == NULL) - tai_leap.sig = emalloc(sign_siglen); - EVP_SignInit(&ctx, sign_digest); - EVP_SignUpdate(&ctx, (u_char *)&tai_leap, 12); - EVP_SignUpdate(&ctx, tai_leap.ptr, - ntohl(tai_leap.vallen)); - if (EVP_SignFinal(&ctx, tai_leap.sig, &len, sign_pkey)) - tai_leap.siglen = htonl(len); + tai_leap.tstamp = hostval.tstamp; + tai_leap.fstamp = hostval.fstamp; + + /* Get the leap second era. We might need a full lookup early + * after start, when the cache is not yet loaded. + */ + leapsec_frame(&leap_data); + if ( ! memcmp(&leap_data.ebase, &leap_data.ttime, sizeof(vint64))) { + time_t now = time(NULL); + uint32_t nowntp = (uint32_t)now + JAN_1970; + leapsec_query(&leap_data, nowntp, &now); } - snprintf(statstr, NTP_MAXSTRLEN, - "update ts %u", ntohl(hostval.tstamp)); + + /* Create the data block. The protocol does not work without. */ + len = 3 * sizeof(u_int32); + if (tai_leap.ptr == NULL || ntohl(tai_leap.vallen) != len) { + free(tai_leap.ptr); + tai_leap.ptr = emalloc(len); + tai_leap.vallen = htonl(len); + } + ptr = (u_int32 *)tai_leap.ptr; + if (leap_data.tai_offs > 10) { + /* create a TAI / leap era block. The end time is a + * fake -- maybe we can do better. + */ + ptr[0] = htonl(leap_data.tai_offs); + ptr[1] = htonl(leap_data.ebase.d_s.lo); + if (leap_data.ttime.d_s.hi >= 0) + ptr[2] = htonl(leap_data.ttime.D_s.lo + 7*86400); + else + ptr[2] = htonl(leap_data.ebase.D_s.lo + 25*86400); + } else { + /* no leap era available */ + memset(ptr, 0, len); + } + if (tai_leap.sig == NULL) + tai_leap.sig = emalloc(sign_siglen); + EVP_SignInit(&ctx, sign_digest); + EVP_SignUpdate(&ctx, (u_char *)&tai_leap, 12); + EVP_SignUpdate(&ctx, tai_leap.ptr, len); + if (EVP_SignFinal(&ctx, tai_leap.sig, &len, sign_pkey)) { + NTP_INSIST(len <= sign_siglen); + tai_leap.siglen = htonl(len); + } + crypto_flags |= CRYPTO_FLAG_TAI; + + snprintf(statstr, sizeof(statstr), "signature update ts %u", + ntohl(hostval.tstamp)); record_crypto_stats(NULL, statstr); -#ifdef DEBUG - if (debug) - printf("crypto_update: %s\n", statstr); -#endif + DPRINTF(1, ("crypto_update: %s\n", statstr)); } +/* + * crypto_update_taichange - eventually trigger crypto_update + * + * This is called when a change in 'sys_tai' is detected. This will + * happen shortly after a leap second is detected, but unhappily also + * early after system start; also, the crypto stuff might be unused and + * an unguarded call to crypto_update() causes a crash. + * + * This function makes sure that there already *is* a valid crypto block + * for the use with autokey, and only calls 'crypto_update()' if it can + * succeed. + * + * Returns void (no errors) + */ +void +crypto_update_taichange(void) +{ + static const u_int len = 3 * sizeof(u_int32); + + /* check if the signing digest algo is available */ + if (sign_digest == NULL || sign_pkey == NULL) + return; + + /* check size of TAI extension block */ + if (tai_leap.ptr == NULL || ntohl(tai_leap.vallen) != len) + return; + + /* crypto_update should at least not crash here! */ + crypto_update(); +} /* * value_free - free value structure components. @@ -2020,12 +1957,14 @@ value_free( /* - * crypto_time - returns current NTP time in seconds. + * crypto_time - returns current NTP time. + * + * Returns NTP seconds if in synch, 0 otherwise */ tstamp_t crypto_time() { - l_fp tstamp; /* NTP time */ L_CLR(&tstamp); + l_fp tstamp; /* NTP time */ L_CLR(&tstamp); if (sys_leap != LEAP_NOTINSYNC) @@ -2035,46 +1974,71 @@ crypto_time() /* - * asn2ntp - convert ASN1_TIME time structure to NTP time in seconds. + * asn_to_calendar - convert ASN1_TIME time structure to struct calendar. + * */ -u_long -asn2ntp ( - ASN1_TIME *asn1time /* pointer to ASN1_TIME structure */ +static +void +asn_to_calendar ( + ASN1_TIME *asn1time, /* pointer to ASN1_TIME structure */ + struct calendar *pjd /* pointer to result */ ) { - char *v; /* pointer to ASN1_TIME string */ - struct tm tm; /* used to convert to NTP time */ + size_t len; /* length of ASN1_TIME string */ + char v[24]; /* writable copy of ASN1_TIME string */ + unsigned long temp; /* result from strtoul */ /* * Extract time string YYMMDDHHMMSSZ from ASN1 time structure. + * Or YYYYMMDDHHMMSSZ. * Note that the YY, MM, DD fields start with one, the HH, MM, - * SS fiels start with zero and the Z character should be 'Z' - * for UTC. Also note that years less than 50 map to years - * greater than 100. Dontcha love ASN.1? Better than MIL-188. - */ - if (asn1time->length > 13) - return ((u_long)(~0)); /* We can't use -1 here. It's invalid */ - - 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 (timegm(&tm) + JAN_1970); + * SS fields start with zero and the Z character is ignored. + * Also note that two-digit years less than 50 map to years greater than + * 100. Dontcha love ASN.1? Better than MIL-188. + */ + len = asn1time->length; + NTP_REQUIRE(len < sizeof(v)); + (void)strncpy(v, (char *)(asn1time->data), len); + NTP_REQUIRE(len >= 13); + temp = strtoul(v+len-3, NULL, 10); + pjd->second = temp; + v[len-3] = '\0'; + + temp = strtoul(v+len-5, NULL, 10); + pjd->minute = temp; + v[len-5] = '\0'; + + temp = strtoul(v+len-7, NULL, 10); + pjd->hour = temp; + v[len-7] = '\0'; + + temp = strtoul(v+len-9, NULL, 10); + pjd->monthday = temp; + v[len-9] = '\0'; + + temp = strtoul(v+len-11, NULL, 10); + pjd->month = temp; + v[len-11] = '\0'; + + temp = strtoul(v, NULL, 10); + /* handle two-digit years */ + if (temp < 50UL) + temp += 100UL; + if (temp < 150UL) + temp += 1900UL; + pjd->year = temp; + + pjd->yearday = pjd->weekday = 0; + return; } /* * bigdig() - compute a BIGNUM MD5 hash of a BIGNUM number. + * + * Returns void (no errors) */ -static int +static void bighash( BIGNUM *bn, /* BIGNUM * from */ BIGNUM *bk /* BIGNUM * to */ @@ -2092,10 +2056,7 @@ bighash( EVP_DigestUpdate(&ctx, ptr, len); EVP_DigestFinal(&ctx, dgst, &len); BN_bin2bn(dgst, len, bk); - - /* XXX MEMLEAK? free ptr? */ - - return (1); + free(ptr); } @@ -2107,35 +2068,38 @@ bighash( *********************************************************************** * * The Schnorr (IFF) identity scheme is intended for use when - * the ntp-genkeys program does not generate the certificates used in - * the protocol and the group key cannot be conveyed in the certificate - * itself. For this purpose, new generations of IFF values must be - * securely transmitted to all members of the group before use. The - * scheme is self contained and independent of new generations of host - * keys, sign keys and certificates. - * - * The IFF identity scheme is based on DSA cryptography and algorithms - * described in Stinson p. 285. The IFF values hide in a DSA cuckoo - * structure, but only the primes and generator are used. The p is a - * 512-bit prime, q a 160-bit prime that divides p - 1 and is a qth root - * of 1 mod p; that is, g^q = 1 mod p. The TA rolls primvate random - * group key b disguised as a DSA structure member, then computes public - * key g^(q - b). These values are shared only among group members and - * never revealed in messages. Alice challenges Bob to confirm identity - * using the protocol described below. + * certificates are generated by some other trusted certificate + * authority and the certificate cannot be used to convey public + * parameters. There are two kinds of files: encrypted server files that + * contain private and public values and nonencrypted client files that + * contain only public values. New generations of server files must be + * securely transmitted to all servers of the group; client files can be + * distributed by any means. The scheme is self contained and + * independent of new generations of host keys, sign keys and + * certificates. + * + * The IFF values hide in a DSA cuckoo structure which uses the same + * parameters. The values are used by an identity scheme based on DSA + * cryptography and described in Stimson p. 285. The p is a 512-bit + * prime, g a generator of Zp* and q a 160-bit prime that divides p - 1 + * and is a qth root of 1 mod p; that is, g^q = 1 mod p. The TA rolls a + * private random group key b (0 < b < q) and public key v = g^b, then + * sends (p, q, g, b) to the servers and (p, q, g, v) to the clients. + * Alice challenges Bob to confirm identity using the protocol described + * below. * * How it works * * The scheme goes like this. Both Alice and Bob have the public primes * p, q and generator g. The TA gives private key b to Bob and public - * key v = g^(q - a) mod p to Alice. - * - * Alice rolls new random challenge r and sends to Bob in the IFF - * request message. Bob rolls new random k, then computes y = k + b r - * mod q and x = g^k mod p and sends (y, hash(x)) to Alice in the - * response message. Besides making the response shorter, the hash makes - * it effectivey impossible for an intruder to solve for b by observing - * a number of these messages. + * key v to Alice. + * + * Alice rolls new random challenge r (o < r < q) and sends to Bob in + * the IFF request message. Bob rolls new random k (0 < k < q), then + * computes y = k + b r mod q and x = g^k mod p and sends (y, hash(x)) + * to Alice in the response message. Besides making the response + * shorter, the hash makes it effectivey impossible for an intruder to + * solve for b by observing a number of these messages. * * Alice receives the response and computes g^y v^r mod p. After a bit * of algebra, this simplifies to g^k. If the hash of this result @@ -2147,8 +2111,8 @@ bighash( * * Returns * XEVNT_OK success - * XEVNT_PUB bad or missing public key * XEVNT_ID bad or missing group key + * XEVNT_PUB bad or missing public key */ static int crypto_alice( @@ -2165,50 +2129,49 @@ crypto_alice( /* * The identity parameters must have correct format and content. */ - if (peer->ident_pkey == NULL) + if (peer->ident_pkey == NULL) { + msyslog(LOG_NOTICE, "crypto_alice: scheme unavailable"); return (XEVNT_ID); + } - if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) { - msyslog(LOG_INFO, "crypto_alice: defective key"); + if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) { + msyslog(LOG_NOTICE, "crypto_alice: defective key"); return (XEVNT_PUB); } /* - * Roll new random r (0 < r < q). The OpenSSL library has a bug - * omitting BN_rand_range, so we have to do it the hard way. + * Roll new random r (0 < r < q). */ - bctx = BN_CTX_new(); - len = BN_num_bytes(dsa->q); if (peer->iffval != NULL) BN_free(peer->iffval); peer->iffval = BN_new(); - BN_rand(peer->iffval, len * 8, -1, 1); /* r */ + len = BN_num_bytes(dsa->q); + BN_rand(peer->iffval, len * 8, -1, 1); /* r mod q*/ + bctx = BN_CTX_new(); BN_mod(peer->iffval, peer->iffval, dsa->q, bctx); BN_CTX_free(bctx); /* * Sign and send to Bob. The filestamp is from the local file. */ - tstamp = crypto_time(); memset(vp, 0, sizeof(struct value)); + tstamp = crypto_time(); vp->tstamp = htonl(tstamp); - vp->fstamp = htonl(peer->fstamp); + vp->fstamp = htonl(peer->ident_pkey->fstamp); vp->vallen = htonl(len); vp->ptr = emalloc(len); BN_bn2bin(peer->iffval, vp->ptr); - vp->siglen = 0; if (tstamp == 0) return (XEVNT_OK); - if (tstamp < cinfo->first || tstamp > cinfo->last) - return (XEVNT_PER); - vp->sig = emalloc(sign_siglen); EVP_SignInit(&ctx, sign_digest); EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12); EVP_SignUpdate(&ctx, vp->ptr, len); - if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) + if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) { + NTP_INSIST(len <= sign_siglen); vp->siglen = htonl(len); + } return (XEVNT_OK); } @@ -2218,9 +2181,8 @@ crypto_alice( * * Returns * XEVNT_OK success - * XEVNT_ID bad or missing group key * XEVNT_ERR protocol error - * XEVNT_PER host expired certificate + * XEVNT_ID bad or missing group key */ static int crypto_bob( @@ -2242,11 +2204,11 @@ crypto_bob( * If the IFF parameters are not valid, something awful * happened or we are being tormented. */ - if (iffpar_pkey == NULL) { - msyslog(LOG_INFO, "crypto_bob: scheme unavailable"); + if (iffkey_info == NULL) { + msyslog(LOG_NOTICE, "crypto_bob: scheme unavailable"); return (XEVNT_ID); } - dsa = iffpar_pkey->pkey.dsa; + dsa = iffkey_info->pkey->pkey.dsa; /* * Extract r from the challenge. @@ -2256,7 +2218,7 @@ crypto_bob( if (vallen == 0 || len < VALUE_LEN || len - VALUE_LEN < vallen) return XEVNT_LEN; if ((r = BN_bin2bn((u_char *)ep->pkt, vallen, NULL)) == NULL) { - msyslog(LOG_ERR, "crypto_bob %s\n", + msyslog(LOG_ERR, "crypto_bob: %s", ERR_error_string(ERR_get_error(), NULL)); return (XEVNT_ERR); } @@ -2277,13 +2239,18 @@ crypto_bob( sdsa->s = BN_dup(bk); BN_CTX_free(bctx); BN_free(r); BN_free(bn); BN_free(bk); +#ifdef DEBUG + if (debug > 1) + DSA_print_fp(stdout, dsa, 0); +#endif /* - * Encode the values in ASN.1 and sign. + * Encode the values in ASN.1 and sign. The filestamp is from + * the local file. */ vallen = i2d_DSA_SIG(sdsa, NULL); if (vallen == 0) { - msyslog(LOG_ERR, "crypto_bob %s\n", + msyslog(LOG_ERR, "crypto_bob: %s", ERR_error_string(ERR_get_error(), NULL)); DSA_SIG_free(sdsa); return (XEVNT_ERR); @@ -2297,26 +2264,24 @@ crypto_bob( memset(vp, 0, sizeof(struct value)); tstamp = crypto_time(); vp->tstamp = htonl(tstamp); - vp->fstamp = htonl(if_fstamp); + vp->fstamp = htonl(iffkey_info->fstamp); vp->vallen = htonl(vallen); ptr = emalloc(vallen); vp->ptr = ptr; i2d_DSA_SIG(sdsa, &ptr); DSA_SIG_free(sdsa); - vp->siglen = 0; if (tstamp == 0) return (XEVNT_OK); - if (tstamp < cinfo->first || tstamp > cinfo->last) - return (XEVNT_PER); - /* XXX: more validation to make sure the sign fits... */ vp->sig = emalloc(sign_siglen); EVP_SignInit(&ctx, sign_digest); EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12); EVP_SignUpdate(&ctx, vp->ptr, vallen); - if (EVP_SignFinal(&ctx, vp->sig, &vallen, sign_pkey)) - vp->siglen = htonl(len); + if (EVP_SignFinal(&ctx, vp->sig, &vallen, sign_pkey)) { + NTP_INSIST(vallen <= sign_siglen); + vp->siglen = htonl(vallen); + } return (XEVNT_OK); } @@ -2326,9 +2291,9 @@ crypto_bob( * * Returns * XEVNT_OK success - * XEVNT_PUB bad or missing public key - * XEVNT_ID bad or missing group key * XEVNT_FSP bad filestamp + * XEVNT_ID bad or missing group key + * XEVNT_PUB bad or missing public key */ int crypto_iff( @@ -2341,7 +2306,7 @@ crypto_iff( DSA_SIG *sdsa; /* DSA parameters */ BIGNUM *bn, *bk; u_int len; - const u_char *ptr; + const u_char *ptr; int temp; /* @@ -2349,20 +2314,20 @@ crypto_iff( * something awful happened or we are being tormented. */ if (peer->ident_pkey == NULL) { - msyslog(LOG_INFO, "crypto_iff: scheme unavailable"); + msyslog(LOG_NOTICE, "crypto_iff: scheme unavailable"); return (XEVNT_ID); } - if (ntohl(ep->fstamp) != peer->fstamp) { - msyslog(LOG_INFO, "crypto_iff: invalid filestamp %u", + if (ntohl(ep->fstamp) != peer->ident_pkey->fstamp) { + msyslog(LOG_NOTICE, "crypto_iff: invalid filestamp %u", ntohl(ep->fstamp)); return (XEVNT_FSP); } - if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) { - msyslog(LOG_INFO, "crypto_iff: defective key"); + if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) { + msyslog(LOG_NOTICE, "crypto_iff: defective key"); return (XEVNT_PUB); } if (peer->iffval == NULL) { - msyslog(LOG_INFO, "crypto_iff: missing challenge"); + msyslog(LOG_NOTICE, "crypto_iff: missing challenge"); return (XEVNT_ID); } @@ -2371,9 +2336,10 @@ crypto_iff( */ bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new(); len = ntohl(ep->vallen); - ptr = (const u_char *)ep->pkt; + ptr = (u_char *)ep->pkt; if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) { - msyslog(LOG_ERR, "crypto_iff %s\n", + BN_free(bn); BN_free(bk); BN_CTX_free(bctx); + msyslog(LOG_ERR, "crypto_iff: %s", ERR_error_string(ERR_get_error(), NULL)); return (XEVNT_ERR); } @@ -2397,8 +2363,8 @@ crypto_iff( if (temp == 0) return (XEVNT_OK); - else - return (XEVNT_ID); + msyslog(LOG_NOTICE, "crypto_iff: identity not verified"); + return (XEVNT_ID); } @@ -2411,20 +2377,25 @@ crypto_iff( *********************************************************************** * * The Guillou-Quisquater (GQ) identity scheme is intended for use when - * the ntp-genkeys program generates the certificates used in the - * protocol and the group key can be conveyed in a certificate extension - * field. The scheme is self contained and independent of new - * generations of host keys, sign keys and certificates. - * - * The GQ identity scheme is based on RSA cryptography and algorithms - * described in Stinson p. 300 (with errors). The GQ values hide in a - * RSA cuckoo structure, but only the modulus is used. The 512-bit - * public modulus is n = p q, where p and q are secret large primes. The - * TA rolls random group key b disguised as a RSA structure member. - * Except for the public key, these values are shared only among group - * members and never revealed in messages. - * - * When rolling new certificates, Bob recomputes the private and + * the certificate can be used to convey public parameters. The scheme + * uses a X509v3 certificate extension field do convey the public key of + * a private key known only to servers. There are two kinds of files: + * encrypted server files that contain private and public values and + * nonencrypted client files that contain only public values. New + * generations of server files must be securely transmitted to all + * servers of the group; client files can be distributed by any means. + * The scheme is self contained and independent of new generations of + * host keys and sign keys. The scheme is self contained and independent + * of new generations of host keys and sign keys. + * + * The GQ parameters hide in a RSA cuckoo structure which uses the same + * parameters. The values are used by an identity scheme based on RSA + * cryptography and described in Stimson p. 300 (with errors). The 512- + * bit public modulus is n = p q, where p and q are secret large primes. + * The TA rolls private random group key b as RSA exponent. These values + * are known to all group members. + * + * When rolling new certificates, a server recomputes the private and * public keys. The private key u is a random roll, while the public key * is the inverse obscured by the group key v = (u^-1)^b. These values * replace the private and public keys normally generated by the RSA @@ -2459,9 +2430,8 @@ crypto_iff( * * Returns * XEVNT_OK success - * XEVNT_PUB bad or missing public key * XEVNT_ID bad or missing group key - * XEVNT_PER host certificate expired + * XEVNT_PUB bad or missing public key */ static int crypto_alice2( @@ -2481,47 +2451,44 @@ crypto_alice2( if (peer->ident_pkey == NULL) return (XEVNT_ID); - if ((rsa = peer->ident_pkey->pkey.rsa) == NULL) { - msyslog(LOG_INFO, "crypto_alice2: defective key"); + if ((rsa = peer->ident_pkey->pkey->pkey.rsa) == NULL) { + msyslog(LOG_NOTICE, "crypto_alice2: defective key"); return (XEVNT_PUB); } /* - * Roll new random r (0 < r < n). The OpenSSL library has a bug - * omitting BN_rand_range, so we have to do it the hard way. + * Roll new random r (0 < r < n). */ - bctx = BN_CTX_new(); - len = BN_num_bytes(rsa->n); if (peer->iffval != NULL) BN_free(peer->iffval); peer->iffval = BN_new(); + len = BN_num_bytes(rsa->n); BN_rand(peer->iffval, len * 8, -1, 1); /* r mod n */ + bctx = BN_CTX_new(); BN_mod(peer->iffval, peer->iffval, rsa->n, bctx); BN_CTX_free(bctx); /* * Sign and send to Bob. The filestamp is from the local file. */ - tstamp = crypto_time(); memset(vp, 0, sizeof(struct value)); + tstamp = crypto_time(); vp->tstamp = htonl(tstamp); - vp->fstamp = htonl(peer->fstamp); + vp->fstamp = htonl(peer->ident_pkey->fstamp); vp->vallen = htonl(len); vp->ptr = emalloc(len); BN_bn2bin(peer->iffval, vp->ptr); - vp->siglen = 0; if (tstamp == 0) return (XEVNT_OK); - if (tstamp < cinfo->first || tstamp > cinfo->last) - return (XEVNT_PER); - vp->sig = emalloc(sign_siglen); EVP_SignInit(&ctx, sign_digest); EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12); EVP_SignUpdate(&ctx, vp->ptr, len); - if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) + if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) { + NTP_INSIST(len <= sign_siglen); vp->siglen = htonl(len); + } return (XEVNT_OK); } @@ -2531,9 +2498,8 @@ crypto_alice2( * * Returns * XEVNT_OK success - * XEVNT_ID bad or missing group key * XEVNT_ERR protocol error - * XEVNT_PER host certificate expired + * XEVNT_ID bad or missing group key */ static int crypto_bob2( @@ -2549,23 +2515,24 @@ crypto_bob2( BIGNUM *r, *k, *g, *y; u_char *ptr; u_int len; + int s_len; /* * If the GQ parameters are not valid, something awful * happened or we are being tormented. */ - if (gqpar_pkey == NULL) { - msyslog(LOG_INFO, "crypto_bob2: scheme unavailable"); + if (gqkey_info == NULL) { + msyslog(LOG_NOTICE, "crypto_bob2: scheme unavailable"); return (XEVNT_ID); } - rsa = gqpar_pkey->pkey.rsa; + rsa = gqkey_info->pkey->pkey.rsa; /* * Extract r from the challenge. */ len = ntohl(ep->vallen); if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) { - msyslog(LOG_ERR, "crypto_bob2 %s\n", + msyslog(LOG_ERR, "crypto_bob2: %s", ERR_error_string(ERR_get_error(), NULL)); return (XEVNT_ERR); } @@ -2586,39 +2553,42 @@ crypto_bob2( sdsa->s = BN_dup(g); BN_CTX_free(bctx); BN_free(r); BN_free(k); BN_free(g); BN_free(y); +#ifdef DEBUG + if (debug > 1) + RSA_print_fp(stdout, rsa, 0); +#endif /* - * Encode the values in ASN.1 and sign. + * Encode the values in ASN.1 and sign. The filestamp is from + * the local file. */ - tstamp = crypto_time(); - memset(vp, 0, sizeof(struct value)); - vp->tstamp = htonl(tstamp); - vp->fstamp = htonl(gq_fstamp); - len = i2d_DSA_SIG(sdsa, NULL); - if (len <= 0) { - msyslog(LOG_ERR, "crypto_bob2 %s\n", + len = s_len = i2d_DSA_SIG(sdsa, NULL); + if (s_len <= 0) { + msyslog(LOG_ERR, "crypto_bob2: %s", ERR_error_string(ERR_get_error(), NULL)); DSA_SIG_free(sdsa); return (XEVNT_ERR); } + memset(vp, 0, sizeof(struct value)); + tstamp = crypto_time(); + vp->tstamp = htonl(tstamp); + vp->fstamp = htonl(gqkey_info->fstamp); vp->vallen = htonl(len); ptr = emalloc(len); vp->ptr = ptr; i2d_DSA_SIG(sdsa, &ptr); DSA_SIG_free(sdsa); - vp->siglen = 0; if (tstamp == 0) return (XEVNT_OK); - if (tstamp < cinfo->first || tstamp > cinfo->last) - return (XEVNT_PER); - vp->sig = emalloc(sign_siglen); EVP_SignInit(&ctx, sign_digest); EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12); EVP_SignUpdate(&ctx, vp->ptr, len); - if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) + if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) { + NTP_INSIST(len <= sign_siglen); vp->siglen = htonl(len); + } return (XEVNT_OK); } @@ -2628,10 +2598,10 @@ crypto_bob2( * * Returns * XEVNT_OK success - * XEVNT_PUB bad or missing public key - * XEVNT_ID bad or missing group keys * XEVNT_ERR protocol error * XEVNT_FSP bad filestamp + * XEVNT_ID bad or missing group keys + * XEVNT_PUB bad or missing public key */ int crypto_gq( @@ -2643,29 +2613,31 @@ crypto_gq( BN_CTX *bctx; /* BIGNUM context */ DSA_SIG *sdsa; /* RSA signature context fake */ BIGNUM *y, *v; - const u_char *ptr; - u_int len; - int temp; + const u_char *ptr; + long len; + u_int temp; /* * If the GQ parameters are not valid or no challenge was sent, - * something awful happened or we are being tormented. + * something awful happened or we are being tormented. Note that + * the filestamp on the local key file can be greater than on + * the remote parameter file if the keys have been refreshed. */ if (peer->ident_pkey == NULL) { - msyslog(LOG_INFO, "crypto_gq: scheme unavailable"); + msyslog(LOG_NOTICE, "crypto_gq: scheme unavailable"); return (XEVNT_ID); } - if (ntohl(ep->fstamp) != peer->fstamp) { - msyslog(LOG_INFO, "crypto_gq: invalid filestamp %u", + if (ntohl(ep->fstamp) < peer->ident_pkey->fstamp) { + msyslog(LOG_NOTICE, "crypto_gq: invalid filestamp %u", ntohl(ep->fstamp)); return (XEVNT_FSP); } - if ((rsa = peer->ident_pkey->pkey.rsa) == NULL) { - msyslog(LOG_INFO, "crypto_gq: defective key"); + if ((rsa = peer->ident_pkey->pkey->pkey.rsa) == NULL) { + msyslog(LOG_NOTICE, "crypto_gq: defective key"); return (XEVNT_PUB); } if (peer->iffval == NULL) { - msyslog(LOG_INFO, "crypto_gq: missing challenge"); + msyslog(LOG_NOTICE, "crypto_gq: missing challenge"); return (XEVNT_ID); } @@ -2675,9 +2647,10 @@ crypto_gq( */ bctx = BN_CTX_new(); y = BN_new(); v = BN_new(); len = ntohl(ep->vallen); - ptr = (const u_char *)ep->pkt; + ptr = (u_char *)ep->pkt; if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) { - msyslog(LOG_ERR, "crypto_gq %s\n", + BN_CTX_free(bctx); BN_free(y); BN_free(v); + msyslog(LOG_ERR, "crypto_gq: %s", ERR_error_string(ERR_get_error(), NULL)); return (XEVNT_ERR); } @@ -2685,6 +2658,10 @@ crypto_gq( /* * Compute v^r y^b mod n. */ + if (peer->grpkey == NULL) { + msyslog(LOG_NOTICE, "crypto_gq: missing group key"); + return (XEVNT_ID); + } BN_mod_exp(v, peer->grpkey, peer->iffval, rsa->n, bctx); /* v^r mod n */ BN_mod_exp(y, sdsa->r, rsa->e, rsa->n, bctx); /* y^b mod n */ @@ -2702,8 +2679,8 @@ crypto_gq( if (temp == 0) return (XEVNT_OK); - else - return (XEVNT_ID); + msyslog(LOG_NOTICE, "crypto_gq: identity not verified"); + return (XEVNT_ID); } @@ -2714,8 +2691,7 @@ crypto_gq( * scheme * * * *********************************************************************** - */ -/* + * * The Mu-Varadharajan (MV) cryptosystem was originally intended when * servers broadcast messages to clients, but clients never send * messages to servers. There is one encryption key for the server and a @@ -2732,19 +2708,16 @@ crypto_gq( * Varadharajan: Robust and Secure Broadcasting, Proc. Indocrypt 2001, * 223-231. The paper has significant errors and serious omissions. * - * Let q be the product of n distinct primes s'[j] (j = 1...n), where - * each s'[j] has m significant bits. Let p be a prime p = 2 * q + 1, so - * that q and each s'[j] divide p - 1 and p has M = n * m + 1 - * significant bits. The elements x mod q of Zq with the elements 2 and - * the primes removed form a field Zq* valid for polynomial arithetic. - * Let g be a generator of Zp; that is, gcd(g, p - 1) = 1 and g^q = 1 - * mod p. We expect M to be in the 500-bit range and n relatively small, - * like 25, so the likelihood of a randomly generated element of x mod q - * of Zq colliding with a factor of p - 1 is very small and can be - * avoided. Associated with each s'[j] is an element s[j] such that s[j] - * s'[j] = s'[j] mod q. We find s[j] as the quotient (q + s'[j]) / - * s'[j]. These are the parameters of the scheme and they are expensive - * to compute. + * Let q be the product of n distinct primes s1[j] (j = 1...n), where + * each s1[j] has m significant bits. Let p be a prime p = 2 * q + 1, so + * that q and each s1[j] divide p - 1 and p has M = n * m + 1 + * significant bits. Let g be a generator of Zp; that is, gcd(g, p - 1) + * = 1 and g^q = 1 mod p. We do modular arithmetic over Zq and then + * project into Zp* as exponents of g. Sometimes we have to compute an + * inverse b^-1 of random b in Zq, but for that purpose we require + * gcd(b, q) = 1. We expect M to be in the 500-bit range and n + * relatively small, like 30. These are the parameters of the scheme and + * they are expensive to compute. * * We set up an instance of the scheme as follows. A set of random * values x[j] mod q (j = 1...n), are generated as the zeros of a @@ -2755,39 +2728,41 @@ crypto_gq( * pairs (xbar[j], xhat[j]) (j = 1...n) of private client keys are used * to construct the decryption keys. The devil is in the details. * + * This routine generates a private server encryption file including the + * private encryption key E and partial decryption keys gbar and ghat. + * It then generates public client decryption files including the public + * keys xbar[j] and xhat[j] for each client j. The partial decryption + * files are used to compute the inverse of E. These values are suitably + * blinded so secrets are not revealed. + * * The distinguishing characteristic of this scheme is the capability to * revoke keys. Included in the calculation of E, gbar and ghat is the - * product s = prod(s'[j]) (j = 1...n) above. If the factor s'[j] is + * product s = prod(s1[j]) (j = 1...n) above. If the factor s1[j] is * subsequently removed from the product and E, gbar and ghat * recomputed, the jth client will no longer be able to compute E^-1 and - * thus unable to decrypt the block. + * thus unable to decrypt the messageblock. * * How it works * - * The scheme goes like this. Bob has the server values (p, A, q, gbar, - * ghat) and Alice the client values (p, xbar, xhat). + * The scheme goes like this. Bob has the server values (p, E, q, gbar, + * ghat) and Alice has the client values (p, xbar, xhat). * - * Alice rolls new random challenge r (0 < r < p) and sends to Bob in - * the MV request message. Bob rolls new random k (0 < k < q), encrypts - * y = A^k mod p (a permutation) and sends (hash(y), gbar^k, ghat^k) to - * Alice. + * Alice rolls new random nonce r mod p and sends to Bob in the MV + * request message. Bob rolls random nonce k mod q, encrypts y = r E^k + * mod p and sends (y, gbar^k, ghat^k) to Alice. * - * Alice receives the response and computes the decryption key (the - * inverse permutation) from previously obtained (xbar, xhat) and - * (gbar^k, ghat^k) in the message. She computes the inverse, which is - * unique by reasons explained in the ntp-keygen.c program sources. If - * the hash of this result matches hash(y), Alice knows that Bob has the - * group key b. The signed response binds this knowledge to Bob's - * private key and the public key previously received in his - * certificate. + * Alice receives the response and computes the inverse (E^k)^-1 from + * the partial decryption keys gbar^k, ghat^k, xbar and xhat. She then + * decrypts y and verifies it matches the original r. The signed + * response binds this knowledge to Bob's private key and the public key + * previously received in his certificate. * * crypto_alice3 - construct Alice's challenge in MV scheme * * Returns * XEVNT_OK success - * XEVNT_PUB bad or missing public key * XEVNT_ID bad or missing group key - * XEVNT_PER host certificate expired + * XEVNT_PUB bad or missing public key */ static int crypto_alice3( @@ -2807,47 +2782,44 @@ crypto_alice3( if (peer->ident_pkey == NULL) return (XEVNT_ID); - if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) { - msyslog(LOG_INFO, "crypto_alice3: defective key"); + if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) { + msyslog(LOG_NOTICE, "crypto_alice3: defective key"); return (XEVNT_PUB); } /* - * Roll new random r (0 < r < q). The OpenSSL library has a bug - * omitting BN_rand_range, so we have to do it the hard way. + * Roll new random r (0 < r < q). */ - bctx = BN_CTX_new(); - len = BN_num_bytes(dsa->p); if (peer->iffval != NULL) BN_free(peer->iffval); peer->iffval = BN_new(); - BN_rand(peer->iffval, len * 8, -1, 1); /* r */ + len = BN_num_bytes(dsa->p); + BN_rand(peer->iffval, len * 8, -1, 1); /* r mod p */ + bctx = BN_CTX_new(); BN_mod(peer->iffval, peer->iffval, dsa->p, bctx); BN_CTX_free(bctx); /* * Sign and send to Bob. The filestamp is from the local file. */ - tstamp = crypto_time(); memset(vp, 0, sizeof(struct value)); + tstamp = crypto_time(); vp->tstamp = htonl(tstamp); - vp->fstamp = htonl(peer->fstamp); + vp->fstamp = htonl(peer->ident_pkey->fstamp); vp->vallen = htonl(len); vp->ptr = emalloc(len); BN_bn2bin(peer->iffval, vp->ptr); - vp->siglen = 0; if (tstamp == 0) return (XEVNT_OK); - if (tstamp < cinfo->first || tstamp > cinfo->last) - return (XEVNT_PER); - vp->sig = emalloc(sign_siglen); EVP_SignInit(&ctx, sign_digest); EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12); EVP_SignUpdate(&ctx, vp->ptr, len); - if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) + if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) { + NTP_INSIST(len <= sign_siglen); vp->siglen = htonl(len); + } return (XEVNT_OK); } @@ -2858,7 +2830,6 @@ crypto_alice3( * Returns * XEVNT_OK success * XEVNT_ERR protocol error - * XEVNT_PER host certificate expired */ static int crypto_bob3( @@ -2879,26 +2850,26 @@ crypto_bob3( * If the MV parameters are not valid, something awful * happened or we are being tormented. */ - if (mvpar_pkey == NULL) { - msyslog(LOG_INFO, "crypto_bob3: scheme unavailable"); + if (mvkey_info == NULL) { + msyslog(LOG_NOTICE, "crypto_bob3: scheme unavailable"); return (XEVNT_ID); } - dsa = mvpar_pkey->pkey.dsa; + dsa = mvkey_info->pkey->pkey.dsa; /* * Extract r from the challenge. */ len = ntohl(ep->vallen); if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) { - msyslog(LOG_ERR, "crypto_bob3 %s\n", + msyslog(LOG_ERR, "crypto_bob3: %s", ERR_error_string(ERR_get_error(), NULL)); return (XEVNT_ERR); } /* * Bob rolls random k (0 < k < q), making sure it is not a - * factor of q. He then computes y = A^k r and sends (hash(y), - * gbar^k, ghat^k) to Alice. + * factor of q. He then computes y = r A^k and sends (y, gbar^k, + * and ghat^k) to Alice. */ bctx = BN_CTX_new(); k = BN_new(); u = BN_new(); sdsa = DSA_new(); @@ -2910,23 +2881,27 @@ crypto_bob3( if (BN_is_one(u)) break; } - BN_mod_exp(u, dsa->g, k, dsa->p, bctx); /* A r */ - BN_mod_mul(u, u, r, dsa->p, bctx); - bighash(u, sdsa->p); + BN_mod_exp(u, dsa->g, k, dsa->p, bctx); /* A^k r */ + BN_mod_mul(sdsa->p, u, r, dsa->p, bctx); BN_mod_exp(sdsa->q, dsa->priv_key, k, dsa->p, bctx); /* gbar */ BN_mod_exp(sdsa->g, dsa->pub_key, k, dsa->p, bctx); /* ghat */ BN_CTX_free(bctx); BN_free(k); BN_free(r); BN_free(u); +#ifdef DEBUG + if (debug > 1) + DSA_print_fp(stdout, sdsa, 0); +#endif /* - * Encode the values in ASN.1 and sign. + * Encode the values in ASN.1 and sign. The filestamp is from + * the local file. */ - tstamp = crypto_time(); memset(vp, 0, sizeof(struct value)); + tstamp = crypto_time(); vp->tstamp = htonl(tstamp); - vp->fstamp = htonl(mv_fstamp); + vp->fstamp = htonl(mvkey_info->fstamp); len = i2d_DSAparams(sdsa, NULL); - if (len <= 0) { - msyslog(LOG_ERR, "crypto_bob3 %s\n", + if (len == 0) { + msyslog(LOG_ERR, "crypto_bob3: %s", ERR_error_string(ERR_get_error(), NULL)); DSA_free(sdsa); return (XEVNT_ERR); @@ -2936,19 +2911,17 @@ crypto_bob3( vp->ptr = ptr; i2d_DSAparams(sdsa, &ptr); DSA_free(sdsa); - vp->siglen = 0; if (tstamp == 0) return (XEVNT_OK); - if (tstamp < cinfo->first || tstamp > cinfo->last) - return (XEVNT_PER); - vp->sig = emalloc(sign_siglen); EVP_SignInit(&ctx, sign_digest); EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12); EVP_SignUpdate(&ctx, vp->ptr, len); - if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) + if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) { + NTP_INSIST(len <= sign_siglen); vp->siglen = htonl(len); + } return (XEVNT_OK); } @@ -2958,10 +2931,10 @@ crypto_bob3( * * Returns * XEVNT_OK success - * XEVNT_PUB bad or missing public key - * XEVNT_ID bad or missing group key * XEVNT_ERR protocol error * XEVNT_FSP bad filestamp + * XEVNT_ID bad or missing group key + * XEVNT_PUB bad or missing public key */ int crypto_mv( @@ -2974,7 +2947,7 @@ crypto_mv( BN_CTX *bctx; /* BIGNUM context */ BIGNUM *k, *u, *v; u_int len; - const u_char *ptr; + const u_char *ptr; int temp; /* @@ -2982,49 +2955,47 @@ crypto_mv( * something awful happened or we are being tormented. */ if (peer->ident_pkey == NULL) { - msyslog(LOG_INFO, "crypto_mv: scheme unavailable"); + msyslog(LOG_NOTICE, "crypto_mv: scheme unavailable"); return (XEVNT_ID); } - if (ntohl(ep->fstamp) != peer->fstamp) { - msyslog(LOG_INFO, "crypto_mv: invalid filestamp %u", + if (ntohl(ep->fstamp) != peer->ident_pkey->fstamp) { + msyslog(LOG_NOTICE, "crypto_mv: invalid filestamp %u", ntohl(ep->fstamp)); return (XEVNT_FSP); } - if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) { - msyslog(LOG_INFO, "crypto_mv: defective key"); + if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) { + msyslog(LOG_NOTICE, "crypto_mv: defective key"); return (XEVNT_PUB); } if (peer->iffval == NULL) { - msyslog(LOG_INFO, "crypto_mv: missing challenge"); + msyslog(LOG_NOTICE, "crypto_mv: missing challenge"); return (XEVNT_ID); } /* - * Extract the (hash(y), gbar, ghat) values from the response. + * Extract the y, gbar and ghat values from the response. */ bctx = BN_CTX_new(); k = BN_new(); u = BN_new(); v = BN_new(); len = ntohl(ep->vallen); - ptr = (const u_char *)ep->pkt; + ptr = (u_char *)ep->pkt; if ((sdsa = d2i_DSAparams(NULL, &ptr, len)) == NULL) { - msyslog(LOG_ERR, "crypto_mv %s\n", + msyslog(LOG_ERR, "crypto_mv: %s", ERR_error_string(ERR_get_error(), NULL)); return (XEVNT_ERR); } /* - * Compute (gbar^xhat ghat^xbar)^-1 mod p. + * Compute (gbar^xhat ghat^xbar) mod p. */ BN_mod_exp(u, sdsa->q, dsa->pub_key, dsa->p, bctx); BN_mod_exp(v, sdsa->g, dsa->priv_key, dsa->p, bctx); BN_mod_mul(u, u, v, dsa->p, bctx); - BN_mod_inverse(u, u, dsa->p, bctx); - BN_mod_mul(v, u, peer->iffval, dsa->p, bctx); + BN_mod_mul(u, u, sdsa->p, dsa->p, bctx); /* - * The result should match the hash of r mod p. + * The result should match r. */ - bighash(v, v); - temp = BN_cmp(v, sdsa->p); + temp = BN_cmp(u, peer->iffval); BN_CTX_free(bctx); BN_free(k); BN_free(u); BN_free(v); BN_free(peer->iffval); peer->iffval = NULL; @@ -3032,8 +3003,8 @@ crypto_mv( if (temp == 0) return (XEVNT_OK); - else - return (XEVNT_ID); + msyslog(LOG_NOTICE, "crypto_mv: identity not verified"); + return (XEVNT_ID); } @@ -3045,187 +3016,6 @@ crypto_mv( *********************************************************************** */ /* - * cert_parse - parse x509 certificate and create info/value structures. - * - * The server certificate includes the version number, issuer name, - * subject name, public key and valid date interval. If the issuer name - * is the same as the subject name, the certificate is self signed and - * valid only if the server is configured as trustable. If the names are - * different, another issuer has signed the server certificate and - * vouched for it. In this case the server certificate is valid if - * verified by the issuer public key. - * - * Returns certificate info/value pointer if valid, NULL if not. - */ -struct cert_info * /* certificate information structure */ -cert_parse( - u_char *asn1cert, /* X509 certificate */ - u_int len, /* certificate length */ - tstamp_t fstamp /* filestamp */ - ) -{ - X509 *cert; /* X509 certificate */ - X509_EXTENSION *ext; /* X509v3 extension */ - struct cert_info *ret; /* certificate info/value */ - BIO *bp; - X509V3_EXT_METHOD *method; - char pathbuf[MAXFILENAME]; - u_char *uptr; - char *ptr; - int temp, cnt, i; - - /* - * Decode ASN.1 objects and construct certificate structure. - */ - uptr = asn1cert; - if ((cert = d2i_X509(NULL, &uptr, len)) == NULL) { - msyslog(LOG_ERR, "cert_parse %s\n", - ERR_error_string(ERR_get_error(), NULL)); - return (NULL); - } - - /* - * Extract version, subject name and public key. - */ - ret = emalloc(sizeof(struct cert_info)); - memset(ret, 0, sizeof(struct cert_info)); - if ((ret->pkey = X509_get_pubkey(cert)) == NULL) { - msyslog(LOG_ERR, "cert_parse %s\n", - ERR_error_string(ERR_get_error(), NULL)); - cert_free(ret); - X509_free(cert); - return (NULL); - } - ret->version = X509_get_version(cert); - X509_NAME_oneline(X509_get_subject_name(cert), pathbuf, - MAXFILENAME - 1); - ptr = strstr(pathbuf, "CN="); - if (ptr == NULL) { - msyslog(LOG_INFO, "cert_parse: invalid subject %s", - pathbuf); - cert_free(ret); - X509_free(cert); - return (NULL); - } - ret->subject = emalloc(strlen(ptr) + 1); - strcpy(ret->subject, ptr + 3); - - /* - * Extract remaining objects. Note that the NTP serial number is - * the NTP seconds at the time of signing, but this might not be - * the case for other authority. We don't bother to check the - * objects at this time, since the real crunch can happen only - * when the time is valid but not yet certificated. - */ - ret->nid = OBJ_obj2nid(cert->cert_info->signature->algorithm); - ret->digest = (const EVP_MD *)EVP_get_digestbynid(ret->nid); - ret->serial = - (u_long)ASN1_INTEGER_get(X509_get_serialNumber(cert)); - X509_NAME_oneline(X509_get_issuer_name(cert), pathbuf, - MAXFILENAME); - if ((ptr = strstr(pathbuf, "CN=")) == NULL) { - msyslog(LOG_INFO, "cert_parse: invalid issuer %s", - pathbuf); - cert_free(ret); - X509_free(cert); - return (NULL); - } - ret->issuer = emalloc(strlen(ptr) + 1); - strcpy(ret->issuer, ptr + 3); - ret->first = asn2ntp(X509_get_notBefore(cert)); - ret->last = asn2ntp(X509_get_notAfter(cert)); - - /* - * Extract extension fields. These are ad hoc ripoffs of - * currently assigned functions and will certainly be changed - * before prime time. - */ - cnt = X509_get_ext_count(cert); - for (i = 0; i < cnt; i++) { - ext = X509_get_ext(cert, i); - method = X509V3_EXT_get(ext); - temp = OBJ_obj2nid(ext->object); - switch (temp) { - - /* - * If a key_usage field is present, we decode whether - * this is a trusted or private certificate. This is - * dorky; all we want is to compare NIDs, but OpenSSL - * insists on BIO text strings. - */ - case 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 DEBUG - if (debug) - printf("cert_parse: %s: %s\n", - OBJ_nid2ln(temp), pathbuf); -#endif - if (strcmp(pathbuf, "Trust Root") == 0) - ret->flags |= CERT_TRUST; - else if (strcmp(pathbuf, "Private") == 0) - ret->flags |= CERT_PRIV; - break; - - /* - * If a NID_subject_key_identifier field is present, it - * contains the GQ public key. - */ - case NID_subject_key_identifier: - ret->grplen = ext->value->length - 2; - ret->grpkey = emalloc(ret->grplen); - memcpy(ret->grpkey, &ext->value->data[2], - ret->grplen); - break; - } - } - - /* - * If certificate is self signed, verify signature. - */ - if (strcmp(ret->subject, ret->issuer) == 0) { - if (!X509_verify(cert, ret->pkey)) { - msyslog(LOG_INFO, - "cert_parse: signature not verified %s", - pathbuf); - cert_free(ret); - X509_free(cert); - return (NULL); - } - } - - /* - * Verify certificate valid times. Note that certificates cannot - * be retroactive. - */ - if (ret->first > ret->last || ret->first < fstamp) { - msyslog(LOG_INFO, - "cert_parse: invalid certificate %s first %u last %u fstamp %u", - ret->subject, ret->first, ret->last, fstamp); - cert_free(ret); - X509_free(cert); - return (NULL); - } - - /* - * Build the value structure to sign and send later. - */ - ret->cert.fstamp = htonl(fstamp); - ret->cert.vallen = htonl(len); - ret->cert.ptr = emalloc(len); - memcpy(ret->cert.ptr, asn1cert, len); -#ifdef DEBUG - if (debug > 1) - X509_print_fp(stdout, cert); -#endif - X509_free(cert); - return (ret); -} - - -/* * cert_sign - sign x509 certificate equest and update value structure. * * The certificate request includes a copy of the host certificate, @@ -3254,10 +3044,10 @@ cert_parse( * * Returns * XEVNT_OK success - * XEVNT_PUB bad or missing public key * XEVNT_CRT bad or missing certificate - * XEVNT_VFY certificate not verified * XEVNT_PER host certificate expired + * XEVNT_PUB bad or missing public key + * XEVNT_VFY certificate not verified */ static int cert_sign( @@ -3273,8 +3063,10 @@ cert_sign( EVP_PKEY *pkey; /* public key */ EVP_MD_CTX ctx; /* message digest context */ tstamp_t tstamp; /* NTP timestamp */ + struct calendar tscal; u_int len; - u_char *ptr; + const u_char *cptr; + u_char *ptr; int i, temp; /* @@ -3286,12 +3078,9 @@ cert_sign( if (tstamp == 0) return (XEVNT_TSP); - if (tstamp < cinfo->first || tstamp > cinfo->last) - return (XEVNT_PER); - - ptr = (u_char *)ep->pkt; - if ((req = d2i_X509(NULL, &ptr, ntohl(ep->vallen))) == NULL) { - msyslog(LOG_ERR, "cert_sign %s\n", + cptr = (void *)ep->pkt; + if ((req = d2i_X509(NULL, &cptr, ntohl(ep->vallen))) == NULL) { + msyslog(LOG_ERR, "cert_sign: %s", ERR_error_string(ERR_get_error(), NULL)); return (XEVNT_CRT); } @@ -3299,16 +3088,17 @@ cert_sign( * Extract public key and check for errors. */ if ((pkey = X509_get_pubkey(req)) == NULL) { - msyslog(LOG_ERR, "cert_sign %s\n", + msyslog(LOG_ERR, "cert_sign: %s", ERR_error_string(ERR_get_error(), NULL)); X509_free(req); return (XEVNT_PUB); } /* - * Generate X509 certificate signed by this server. For this - * purpose the issuer name is the server name. Also copy any - * extensions that might be present. + * Generate X509 certificate signed by this server. If this is a + * trusted host, the issuer name is the group name; otherwise, + * it is the host name. Also copy any extensions that might be + * present. */ cert = X509_new(); X509_set_version(cert, X509_get_version(req)); @@ -3319,24 +3109,30 @@ cert_sign( X509_gmtime_adj(X509_get_notAfter(cert), YEAR); subj = X509_get_issuer_name(cert); X509_NAME_add_entry_by_txt(subj, "commonName", MBSTRING_ASC, - (u_char *)sys_hostname, strlen(sys_hostname), -1, 0); + hostval.ptr, strlen((const char *)hostval.ptr), -1, 0); subj = X509_get_subject_name(req); X509_set_subject_name(cert, subj); X509_set_pubkey(cert, pkey); - ext = X509_get_ext(req, 0); temp = X509_get_ext_count(req); for (i = 0; i < temp; i++) { ext = X509_get_ext(req, i); - X509_add_ext(cert, ext, -1); + INSIST(X509_add_ext(cert, ext, -1)); } X509_free(req); /* - * Sign and verify the certificate. + * Sign and verify the client certificate, but only if the host + * certificate has not expired. */ + (void)ntpcal_ntp_to_date(&tscal, tstamp, NULL); + if ((calcomp(&tscal, &(cert_host->first)) < 0) + || (calcomp(&tscal, &(cert_host->last)) > 0)) { + X509_free(cert); + return (XEVNT_PER); + } X509_sign(cert, sign_pkey, sign_digest); - if (!X509_verify(cert, sign_pkey)) { - printf("cert_sign\n%s\n", + if (X509_verify(cert, sign_pkey) <= 0) { + msyslog(LOG_ERR, "cert_sign: %s", ERR_error_string(ERR_get_error(), NULL)); X509_free(cert); return (XEVNT_VFY); @@ -3354,14 +3150,18 @@ cert_sign( vp->vallen = htonl(len); vp->ptr = emalloc(len); ptr = vp->ptr; - i2d_X509(cert, &ptr); + i2d_X509(cert, (unsigned char **)(intptr_t)&ptr); vp->siglen = 0; - vp->sig = emalloc(sign_siglen); - EVP_SignInit(&ctx, sign_digest); - EVP_SignUpdate(&ctx, (u_char *)vp, 12); - EVP_SignUpdate(&ctx, vp->ptr, len); - if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) - vp->siglen = htonl(len); + if (tstamp != 0) { + vp->sig = emalloc(sign_siglen); + EVP_SignInit(&ctx, sign_digest); + EVP_SignUpdate(&ctx, (u_char *)vp, 12); + EVP_SignUpdate(&ctx, vp->ptr, len); + if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) { + NTP_INSIST(len <= sign_siglen); + vp->siglen = htonl(len); + } + } #ifdef DEBUG if (debug > 1) X509_print_fp(stdout, cert); @@ -3372,74 +3172,38 @@ cert_sign( /* - * cert_valid - verify certificate with given public key - * - * This is pretty ugly, as the certificate has to be verified in the - * OpenSSL X509 structure, not in the DER format in the info/value - * structure. - * - * Returns - * XEVNT_OK success - * XEVNT_VFY certificate not verified - */ -int -cert_valid( - struct cert_info *cinf, /* certificate information structure */ - EVP_PKEY *pkey /* public key */ - ) -{ - X509 *cert; /* X509 certificate */ - u_char *ptr; - - if (cinf->flags & CERT_SIGN) - return (XEVNT_OK); - - ptr = (u_char *)cinf->cert.ptr; - cert = d2i_X509(NULL, &ptr, ntohl(cinf->cert.vallen)); - if (cert == NULL || !X509_verify(cert, pkey)) - return (XEVNT_VFY); - - X509_free(cert); - return (XEVNT_OK); -} - - -/* - * cert - install certificate in certificate list + * cert_install - install certificate in certificate cache * * This routine encodes an extension field into a certificate info/value * structure. It searches the certificate list for duplicates and - * expunges whichever is older. It then searches the list for other - * certificates that might be verified by this latest one. Finally, it - * inserts this certificate first on the list. + * expunges whichever is older. Finally, it inserts this certificate + * first on the list. * - * Returns - * XEVNT_OK success - * XEVNT_FSP bad or missing filestamp - * XEVNT_CRT bad or missing certificate + * Returns certificate info pointer if valid, NULL if not. */ -int +struct cert_info * cert_install( struct exten *ep, /* cert info/value */ struct peer *peer /* peer structure */ ) { - struct cert_info *cp, *xp, *yp, **zp; + struct cert_info *cp, *xp, **zp; /* * Parse and validate the signed certificate. If valid, - * construct the info/value structure; otherwise, scamper home. + * construct the info/value structure; otherwise, scamper home + * empty handed. */ - if ((cp = cert_parse((u_char *)ep->pkt, ntohl(ep->vallen), - ntohl(ep->fstamp))) == NULL) - return (XEVNT_CRT); + if ((cp = cert_parse((u_char *)ep->pkt, (long)ntohl(ep->vallen), + (tstamp_t)ntohl(ep->fstamp))) == NULL) + return (NULL); /* * Scan certificate list looking for another certificate with * the same subject and issuer. If another is found with the * same or older filestamp, unlink it and return the goodies to * the heap. If another is found with a later filestamp, discard - * the new one and leave the building. + * the new one and leave the building with the old one. * * Make a note to study this issue again. An earlier certificate * with a long lifetime might be overtaken by a later @@ -3447,112 +3211,314 @@ cert_install( * earlier signature. However, we gotta find a way to leak old * stuff from the cache, so we do it anyway. */ - yp = cp; zp = &cinfo; for (xp = cinfo; xp != NULL; xp = xp->link) { if (strcmp(cp->subject, xp->subject) == 0 && strcmp(cp->issuer, xp->issuer) == 0) { if (ntohl(cp->cert.fstamp) <= ntohl(xp->cert.fstamp)) { - *zp = xp->link;; - cert_free(xp); - } else { cert_free(cp); - return (XEVNT_FSP); + cp = xp; + } else { + *zp = xp->link; + cert_free(xp); + xp = NULL; } break; } zp = &xp->link; } - yp->link = cinfo; - cinfo = yp; + if (xp == NULL) { + cp->link = cinfo; + cinfo = cp; + } + cp->flags |= CERT_VALID; + crypto_update(); + return (cp); +} + + +/* + * cert_hike - verify the signature using the issuer public key + * + * Returns + * XEVNT_OK success + * XEVNT_CRT bad or missing certificate + * XEVNT_PER host certificate expired + * XEVNT_VFY certificate not verified + */ +int +cert_hike( + struct peer *peer, /* peer structure pointer */ + struct cert_info *yp /* issuer certificate */ + ) +{ + struct cert_info *xp; /* subject certificate */ + X509 *cert; /* X509 certificate */ + const u_char *ptr; /* - * Scan the certificate list to see if Y is signed by X. This is - * independent of order. + * Save the issuer on the new certificate, but remember the old + * one. */ - for (yp = cinfo; yp != NULL; yp = yp->link) { - for (xp = cinfo; xp != NULL; xp = xp->link) { + if (peer->issuer != NULL) + free(peer->issuer); + peer->issuer = estrdup(yp->issuer); + xp = peer->xinfo; + peer->xinfo = yp; - /* - * If the issuer of certificate Y matches the - * subject of certificate X, verify the - * signature of Y using the public key of X. If - * so, X signs Y. - */ - if (strcmp(yp->issuer, xp->subject) != 0 || - xp->flags & CERT_ERROR) - continue; + /* + * If subject Y matches issuer Y, then the certificate trail is + * complete. If Y is not trusted, the server certificate has yet + * been signed, so keep trying. Otherwise, save the group key + * and light the valid bit. If the host certificate is trusted, + * do not execute a sign exchange. If no identity scheme is in + * use, light the identity and proventic bits. + */ + if (strcmp(yp->subject, yp->issuer) == 0) { + if (!(yp->flags & CERT_TRUST)) + return (XEVNT_OK); - if (cert_valid(yp, xp->pkey) != XEVNT_OK) { - yp->flags |= CERT_ERROR; - continue; - } + /* + * If the server has an an identity scheme, fetch the + * identity credentials. If not, the identity is + * verified only by the trusted certificate. The next + * signature will set the server proventic. + */ + peer->crypto |= CRYPTO_FLAG_CERT; + peer->grpkey = yp->grpkey; + if (peer->ident == NULL || !(peer->crypto & + CRYPTO_FLAG_MASK)) + peer->crypto |= CRYPTO_FLAG_VRFY; + } - /* - * The signature Y is valid only if it begins - * during the lifetime of X; however, it is not - * necessarily an error, since some other - * certificate might sign Y. - */ - if (yp->first < xp->first || yp->first > - xp->last) - continue; + /* + * If X exists, verify signature X using public key Y. + */ + if (xp == NULL) + return (XEVNT_OK); - yp->flags |= CERT_SIGN; + ptr = (u_char *)xp->cert.ptr; + cert = d2i_X509(NULL, &ptr, ntohl(xp->cert.vallen)); + if (cert == NULL) { + xp->flags |= CERT_ERROR; + return (XEVNT_CRT); + } + if (X509_verify(cert, yp->pkey) <= 0) { + X509_free(cert); + xp->flags |= CERT_ERROR; + return (XEVNT_VFY); + } + X509_free(cert); - /* - * If X is trusted, then Y is trusted. Note that - * we might stumble over a self-signed - * certificate that is not trusted, at least - * temporarily. This can happen when a dude - * first comes up, but has not synchronized the - * clock and had its certificate signed by its - * server. In case of broken certificate trail, - * this might result in a loop that could - * persist until timeout. - */ - if (!(xp->flags & (CERT_TRUST | CERT_VALID))) - continue; + /* + * Signature X is valid only if it begins during the + * lifetime of Y. + */ + if ((calcomp(&(xp->first), &(yp->first)) < 0) + || (calcomp(&(xp->first), &(yp->last)) > 0)) { + xp->flags |= CERT_ERROR; + return (XEVNT_PER); + } + xp->flags |= CERT_SIGN; + return (XEVNT_OK); +} - yp->flags |= CERT_VALID; - /* - * If subject Y matches the server subject name, - * then Y has completed the certificate trail. - * Save the group key and light the valid bit. - */ - if (strcmp(yp->subject, peer->subject) != 0) - continue; +/* + * cert_parse - parse x509 certificate and create info/value structures. + * + * The server certificate includes the version number, issuer name, + * subject name, public key and valid date interval. If the issuer name + * is the same as the subject name, the certificate is self signed and + * valid only if the server is configured as trustable. If the names are + * different, another issuer has signed the server certificate and + * vouched for it. In this case the server certificate is valid if + * verified by the issuer public key. + * + * Returns certificate info/value pointer if valid, NULL if not. + */ +struct cert_info * /* certificate information structure */ +cert_parse( + const u_char *asn1cert, /* X509 certificate */ + long len, /* certificate length */ + tstamp_t fstamp /* filestamp */ + ) +{ + X509 *cert; /* X509 certificate */ + X509_EXTENSION *ext; /* X509v3 extension */ + struct cert_info *ret; /* certificate info/value */ + BIO *bp; + char pathbuf[MAXFILENAME]; + const u_char *ptr; + char *pch; + int temp, cnt, i; + struct calendar fscal; - if (yp->grpkey != NULL) { - if (peer->grpkey != NULL) - BN_free(peer->grpkey); - peer->grpkey = BN_bin2bn(yp->grpkey, - yp->grplen, NULL); - } - peer->crypto |= CRYPTO_FLAG_VALID; + /* + * Decode ASN.1 objects and construct certificate structure. + */ + ptr = asn1cert; + if ((cert = d2i_X509(NULL, &ptr, len)) == NULL) { + msyslog(LOG_ERR, "cert_parse: %s", + ERR_error_string(ERR_get_error(), NULL)); + return (NULL); + } +#ifdef DEBUG + if (debug > 1) + X509_print_fp(stdout, cert); +#endif - /* - * If the server has an an identity scheme, - * fetch the identity credentials. If not, the - * identity is verified only by the trusted - * certificate. The next signature will set the - * server proventic. - */ - if (peer->crypto & (CRYPTO_FLAG_GQ | - CRYPTO_FLAG_IFF | CRYPTO_FLAG_MV)) - continue; + /* + * Extract version, subject name and public key. + */ + ret = emalloc_zero(sizeof(*ret)); + if ((ret->pkey = X509_get_pubkey(cert)) == NULL) { + msyslog(LOG_ERR, "cert_parse: %s", + ERR_error_string(ERR_get_error(), NULL)); + cert_free(ret); + X509_free(cert); + return (NULL); + } + ret->version = X509_get_version(cert); + X509_NAME_oneline(X509_get_subject_name(cert), pathbuf, + sizeof(pathbuf)); + pch = strstr(pathbuf, "CN="); + if (NULL == pch) { + msyslog(LOG_NOTICE, "cert_parse: invalid subject %s", + pathbuf); + cert_free(ret); + X509_free(cert); + return (NULL); + } + ret->subject = estrdup(pch + 3); - peer->crypto |= CRYPTO_FLAG_VRFY; + /* + * Extract remaining objects. Note that the NTP serial number is + * the NTP seconds at the time of signing, but this might not be + * the case for other authority. We don't bother to check the + * objects at this time, since the real crunch can happen only + * when the time is valid but not yet certificated. + */ + ret->nid = OBJ_obj2nid(cert->cert_info->signature->algorithm); + ret->digest = (const EVP_MD *)EVP_get_digestbynid(ret->nid); + ret->serial = + (u_long)ASN1_INTEGER_get(X509_get_serialNumber(cert)); + X509_NAME_oneline(X509_get_issuer_name(cert), pathbuf, + sizeof(pathbuf)); + if ((pch = strstr(pathbuf, "CN=")) == NULL) { + msyslog(LOG_NOTICE, "cert_parse: invalid issuer %s", + pathbuf); + cert_free(ret); + X509_free(cert); + return (NULL); + } + ret->issuer = estrdup(pch + 3); + asn_to_calendar(X509_get_notBefore(cert), &(ret->first)); + asn_to_calendar(X509_get_notAfter(cert), &(ret->last)); + + /* + * Extract extension fields. These are ad hoc ripoffs of + * currently assigned functions and will certainly be changed + * before prime time. + */ + cnt = X509_get_ext_count(cert); + for (i = 0; i < cnt; i++) { + ext = X509_get_ext(cert, i); + temp = OBJ_obj2nid(ext->object); + switch (temp) { + + /* + * If a key_usage field is present, we decode whether + * this is a trusted or private certificate. This is + * dorky; all we want is to compare NIDs, but OpenSSL + * insists on BIO text strings. + */ + case NID_ext_key_usage: + bp = BIO_new(BIO_s_mem()); + X509V3_EXT_print(bp, ext, 0, 0); + BIO_gets(bp, pathbuf, sizeof(pathbuf)); + BIO_free(bp); + if (strcmp(pathbuf, "Trust Root") == 0) + ret->flags |= CERT_TRUST; + else if (strcmp(pathbuf, "Private") == 0) + ret->flags |= CERT_PRIV; + DPRINTF(1, ("cert_parse: %s: %s\n", + OBJ_nid2ln(temp), pathbuf)); + break; + + /* + * If a NID_subject_key_identifier field is present, it + * contains the GQ public key. + */ + case NID_subject_key_identifier: + ret->grpkey = BN_bin2bn(&ext->value->data[2], + ext->value->length - 2, NULL); + /* fall through */ + default: + DPRINTF(1, ("cert_parse: %s\n", + OBJ_nid2ln(temp))); + break; + } + } + if (strcmp(ret->subject, ret->issuer) == 0) { + + /* + * If certificate is self signed, verify signature. + */ + if (X509_verify(cert, ret->pkey) <= 0) { + msyslog(LOG_NOTICE, + "cert_parse: signature not verified %s", + ret->subject); + cert_free(ret); + X509_free(cert); + return (NULL); + } + } else { + + /* + * Check for a certificate loop. + */ + if (strcmp((const char *)hostval.ptr, ret->issuer) == 0) { + msyslog(LOG_NOTICE, + "cert_parse: certificate trail loop %s", + ret->subject); + cert_free(ret); + X509_free(cert); + return (NULL); } } /* - * That was awesome. Now update the timestamps and signatures. + * Verify certificate valid times. Note that certificates cannot + * be retroactive. */ - crypto_update(); - return (XEVNT_OK); + (void)ntpcal_ntp_to_date(&fscal, fstamp, NULL); + if ((calcomp(&(ret->first), &(ret->last)) > 0) + || (calcomp(&(ret->first), &fscal) < 0)) { + msyslog(LOG_NOTICE, + "cert_parse: invalid times %s first %u-%02u-%02uT%02u:%02u:%02u last %u-%02u-%02uT%02u:%02u:%02u fstamp %u-%02u-%02uT%02u:%02u:%02u", + ret->subject, + ret->first.year, ret->first.month, ret->first.monthday, + ret->first.hour, ret->first.minute, ret->first.second, + ret->last.year, ret->last.month, ret->last.monthday, + ret->last.hour, ret->last.minute, ret->last.second, + fscal.year, fscal.month, fscal.monthday, + fscal.hour, fscal.minute, fscal.second); + cert_free(ret); + X509_free(cert); + return (NULL); + } + + /* + * Build the value structure to sign and send later. + */ + ret->cert.fstamp = htonl(fstamp); + ret->cert.vallen = htonl(len); + ret->cert.ptr = emalloc(len); + memcpy(ret->cert.ptr, asn1cert, len); + X509_free(cert); + return (ret); } @@ -3571,50 +3537,56 @@ cert_free( if (cinf->issuer != NULL) free(cinf->issuer); if (cinf->grpkey != NULL) - free(cinf->grpkey); + BN_free(cinf->grpkey); value_free(&cinf->cert); free(cinf); } /* - *********************************************************************** - * * - * The following routines are used only at initialization time * - * * - *********************************************************************** - */ -/* - * crypto_key - load cryptographic parameters and keys from files - * - * This routine loads a PEM-encoded public/private key pair and extracts - * the filestamp from the file name. - * - * Returns public key pointer if valid, NULL if not. Side effect updates - * the filestamp if valid. + * crypto_key - load cryptographic parameters and keys + * + * This routine searches the key cache for matching name in the form + * ntpkey_<key>_<name>, where <key> is one of host, sign, iff, gq, mv, + * and <name> is the host/group name. If not found, it tries to load a + * PEM-encoded file of the same name and extracts the filestamp from + * the first line of the file name. It returns the key pointer if valid, + * NULL if not. */ -static EVP_PKEY * +static struct pkey_info * crypto_key( char *cp, /* file name */ - tstamp_t *fstamp /* filestamp */ + char *passwd1, /* password */ + sockaddr_u *addr /* IP address */ ) { FILE *str; /* file handle */ + struct pkey_info *pkp; /* generic key */ EVP_PKEY *pkey = NULL; /* public/private key */ + tstamp_t fstamp; char filename[MAXFILENAME]; /* name of key file */ char linkname[MAXFILENAME]; /* filestamp buffer) */ char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */ char *ptr; /* + * Search the key cache for matching key and name. + */ + for (pkp = pkinfo; pkp != NULL; pkp = pkp->link) { + if (strcmp(cp, pkp->name) == 0) + return (pkp); + } + + /* * Open the key file. If the first character of the file name is * not '/', prepend the keys directory string. If something goes * wrong, abandon ship. */ if (*cp == '/') - strcpy(filename, cp); + strlcpy(filename, cp, sizeof(filename)); else - snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp); + snprintf(filename, sizeof(filename), "%s/%s", keysdir, + cp); str = fopen(filename, "r"); if (str == NULL) return (NULL); @@ -3622,65 +3594,83 @@ crypto_key( /* * Read the filestamp, which is contained in the first line. */ - if ((ptr = fgets(linkname, MAXFILENAME, str)) == NULL) { - msyslog(LOG_ERR, "crypto_key: no data %s\n", + if ((ptr = fgets(linkname, sizeof(linkname), str)) == NULL) { + msyslog(LOG_ERR, "crypto_key: empty file %s", filename); - (void)fclose(str); + fclose(str); return (NULL); } if ((ptr = strrchr(ptr, '.')) == NULL) { - msyslog(LOG_ERR, "crypto_key: no filestamp %s\n", + msyslog(LOG_ERR, "crypto_key: no filestamp %s", filename); - (void)fclose(str); + fclose(str); return (NULL); } - if (sscanf(++ptr, "%u", fstamp) != 1) { - msyslog(LOG_ERR, "crypto_key: invalid timestamp %s\n", + if (sscanf(++ptr, "%u", &fstamp) != 1) { + msyslog(LOG_ERR, "crypto_key: invalid filestamp %s", filename); - (void)fclose(str); + fclose(str); return (NULL); } /* - * Read and decrypt PEM-encoded private key. + * Read and decrypt PEM-encoded private key. If it fails to + * decrypt, game over. */ - pkey = PEM_read_PrivateKey(str, NULL, NULL, passwd); + pkey = PEM_read_PrivateKey(str, NULL, NULL, passwd1); fclose(str); if (pkey == NULL) { - msyslog(LOG_ERR, "crypto_key %s\n", + msyslog(LOG_ERR, "crypto_key: %s", ERR_error_string(ERR_get_error(), NULL)); - return (NULL); + exit (-1); } /* + * Make a new entry in the key cache. + */ + pkp = emalloc(sizeof(struct pkey_info)); + pkp->link = pkinfo; + pkinfo = pkp; + pkp->pkey = pkey; + pkp->name = estrdup(cp); + pkp->fstamp = fstamp; + + /* * Leave tracks in the cryptostats. */ if ((ptr = strrchr(linkname, '\n')) != NULL) *ptr = '\0'; - snprintf(statstr, NTP_MAXSTRLEN, "%s mod %d", &linkname[2], + snprintf(statstr, sizeof(statstr), "%s mod %d", &linkname[2], EVP_PKEY_size(pkey) * 8); - record_crypto_stats(NULL, statstr); + record_crypto_stats(addr, statstr); + + DPRINTF(1, ("crypto_key: %s\n", statstr)); #ifdef DEBUG - if (debug) - printf("crypto_key: %s\n", statstr); if (debug > 1) { if (pkey->type == EVP_PKEY_DSA) DSA_print_fp(stdout, pkey->pkey.dsa, 0); - else + else if (pkey->type == EVP_PKEY_RSA) RSA_print_fp(stdout, pkey->pkey.rsa, 0); } #endif - return (pkey); + return (pkp); } /* + *********************************************************************** + * * + * The following routines are used only at initialization time * + * * + *********************************************************************** + */ +/* * crypto_cert - load certificate from file * - * This routine loads a X.509 RSA or DSA certificate from a file and + * This routine loads an X.509 RSA or DSA certificate from a file and * constructs a info/cert value structure for this machine. The * structure includes a filestamp extracted from the file name. Later - * the certificate can be sent to another machine by request. + * the certificate can be sent to another machine on request. * * Returns certificate info/value pointer if valid, NULL if not. */ @@ -3706,9 +3696,10 @@ crypto_cert( * something goes wrong, abandon ship. */ if (*cp == '/') - strcpy(filename, cp); + strlcpy(filename, cp, sizeof(filename)); else - snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp); + snprintf(filename, sizeof(filename), "%s/%s", keysdir, + cp); str = fopen(filename, "r"); if (str == NULL) return (NULL); @@ -3716,22 +3707,22 @@ crypto_cert( /* * Read the filestamp, which is contained in the first line. */ - if ((ptr = fgets(linkname, MAXFILENAME, str)) == NULL) { - msyslog(LOG_ERR, "crypto_cert: no data %s\n", + if ((ptr = fgets(linkname, sizeof(linkname), str)) == NULL) { + msyslog(LOG_ERR, "crypto_cert: empty file %s", filename); - (void)fclose(str); + fclose(str); return (NULL); } if ((ptr = strrchr(ptr, '.')) == NULL) { - msyslog(LOG_ERR, "crypto_cert: no filestamp %s\n", + msyslog(LOG_ERR, "crypto_cert: no filestamp %s", filename); - (void)fclose(str); + fclose(str); return (NULL); } if (sscanf(++ptr, "%u", &fstamp) != 1) { - msyslog(LOG_ERR, "crypto_cert: invalid filestamp %s\n", + msyslog(LOG_ERR, "crypto_cert: invalid filestamp %s", filename); - (void)fclose(str); + fclose(str); return (NULL); } @@ -3739,266 +3730,144 @@ crypto_cert( * Read PEM-encoded certificate and install. */ if (!PEM_read(str, &name, &header, &data, &len)) { - msyslog(LOG_ERR, "crypto_cert %s\n", + msyslog(LOG_ERR, "crypto_cert: %s", ERR_error_string(ERR_get_error(), NULL)); - (void)fclose(str); + fclose(str); return (NULL); } + fclose(str); free(header); - if (strcmp(name, "CERTIFICATE") !=0) { - msyslog(LOG_INFO, "crypto_cert: wrong PEM type %s", + if (strcmp(name, "CERTIFICATE") != 0) { + msyslog(LOG_NOTICE, "crypto_cert: wrong PEM type %s", name); free(name); free(data); - (void)fclose(str); return (NULL); } free(name); /* - * Parse certificate and generate info/value structure. + * Parse certificate and generate info/value structure. The + * pointer and copy nonsense is due something broken in Solaris. */ ret = cert_parse(data, len, fstamp); free(data); - (void)fclose(str); if (ret == NULL) return (NULL); if ((ptr = strrchr(linkname, '\n')) != NULL) *ptr = '\0'; - snprintf(statstr, NTP_MAXSTRLEN, - "%s 0x%x len %lu", &linkname[2], ret->flags, len); + snprintf(statstr, sizeof(statstr), "%s 0x%x len %lu", + &linkname[2], ret->flags, len); record_crypto_stats(NULL, statstr); -#ifdef DEBUG - if (debug) - printf("crypto_cert: %s\n", statstr); -#endif + DPRINTF(1, ("crypto_cert: %s\n", statstr)); return (ret); } /* - * crypto_tai - load leapseconds table from file - * - * This routine loads the ERTS leapsecond file in NIST text format, - * converts to a value structure and extracts a filestamp from the file - * name. The data are used to establish the TAI offset from UTC, which - * is provided to the kernel if supported. Later the data can be sent to - * another machine on request. - */ -static void -crypto_tai( - char *cp /* file name */ - ) -{ - FILE *str; /* file handle */ - char buf[NTP_MAXSTRLEN]; /* file line buffer */ - u_int32 leapsec[MAX_LEAP]; /* NTP time at leaps */ - int offset; /* offset at leap (s) */ - char filename[MAXFILENAME]; /* name of leapseconds file */ - char linkname[MAXFILENAME]; /* file link (for filestamp) */ - char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */ - tstamp_t fstamp; /* filestamp */ - u_int len; - u_int32 *ptr; - char *dp; - int rval, i, j; - - /* - * Open the file and discard comment lines. If the first - * character of the file name is not '/', prepend the keys - * directory string. If the file is not found, not to worry; it - * can be retrieved over the net. But, if it is found with - * errors, we crash and burn. - */ - if (*cp == '/') - strcpy(filename, cp); - else - snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp); - if ((str = fopen(filename, "r")) == NULL) - return; - - /* - * Extract filestamp if present. - */ - rval = readlink(filename, linkname, MAXFILENAME - 1); - if (rval > 0) { - linkname[rval] = '\0'; - dp = strrchr(linkname, '.'); - } else { - dp = strrchr(filename, '.'); - } - if (dp != NULL) - sscanf(++dp, "%u", &fstamp); - else - fstamp = 0; - tai_leap.fstamp = htonl(fstamp); - - /* - * We are rather paranoid here, since an intruder might cause a - * coredump by infiltrating naughty values. Empty lines and - * comments are ignored. Other lines must begin with two - * integers followed by junk or comments. The first integer is - * the NTP seconds of leap insertion, the second is the offset - * of TAI relative to UTC after that insertion. The second word - * must equal the initial insertion of ten seconds on 1 January - * 1972 plus one second for each succeeding insertion. - */ - i = 0; - while (i < MAX_LEAP) { - dp = fgets(buf, NTP_MAXSTRLEN - 1, str); - if (dp == NULL) - break; - - if (strlen(buf) < 1) - continue; - - if (*buf == '#') - continue; - - if (sscanf(buf, "%u %d", &leapsec[i], &offset) != 2) - continue; - - if (i != offset - TAI_1972) - break; - - i++; - } - fclose(str); - if (dp != NULL) { - msyslog(LOG_INFO, - "crypto_tai: leapseconds file %s error %d", cp, - rval); - exit (-1); - } - - /* - * The extension field table entries consists of the NTP seconds - * of leap insertion in network byte order. - */ - len = i * sizeof(u_int32); - tai_leap.vallen = htonl(len); - ptr = emalloc(len); - tai_leap.ptr = (u_char *)ptr; - for (j = 0; j < i; j++) - *ptr++ = htonl(leapsec[j]); - crypto_flags |= CRYPTO_FLAG_TAI; - snprintf(statstr, NTP_MAXSTRLEN, "%s fs %u leap %u len %u", cp, fstamp, - leapsec[--j], len); - record_crypto_stats(NULL, statstr); -#ifdef DEBUG - if (debug) - printf("crypto_tai: %s\n", statstr); -#endif -} - - -/* - * crypto_setup - load keys, certificate and leapseconds table + * crypto_setup - load keys, certificate and identity parameters * * This routine loads the public/private host key and certificate. If * available, it loads the public/private sign key, which defaults to - * the host key, and leapseconds table. The host key must be RSA, but - * the sign key can be either RSA or DSA. In either case, the public key - * on the certificate must agree with the sign key. + * the host key. The host key must be RSA, but the sign key can be + * either RSA or DSA. If a trusted certificate, it loads the identity + * parameters. In either case, the public key on the certificate must + * agree with the sign key. + * + * Required but missing files and inconsistent data and errors are + * fatal. Allowing configuration to continue would be hazardous and + * require really messy error checks. */ void crypto_setup(void) { - EVP_PKEY *pkey; /* private/public key pair */ + struct pkey_info *pinfo; /* private/public key */ char filename[MAXFILENAME]; /* file name buffer */ + char hostname[MAXFILENAME]; /* host name buffer */ + char *randfile; + char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */ l_fp seed; /* crypto PRNG seed as NTP timestamp */ - tstamp_t fstamp; /* filestamp */ - tstamp_t sstamp; /* sign filestamp */ - u_int len, bytes; + u_int len; + int bytes; u_char *ptr; /* - * Initialize structures. + * Check for correct OpenSSL version and avoid initialization in + * the case of multiple crypto commands. */ - if (!crypto_flags) + if (crypto_flags & CRYPTO_FLAG_ENAB) { + msyslog(LOG_NOTICE, + "crypto_setup: spurious crypto command"); return; - - gethostname(filename, MAXFILENAME); - bytes = strlen(filename) + 1; - sys_hostname = emalloc(bytes); - memcpy(sys_hostname, filename, bytes); - if (passwd == NULL) - passwd = sys_hostname; - memset(&hostval, 0, sizeof(hostval)); - memset(&pubkey, 0, sizeof(pubkey)); - memset(&tai_leap, 0, sizeof(tai_leap)); + } + ssl_check_version(); /* * Load required random seed file and seed the random number - * generator. Be default, it is found in the user home + * generator. Be default, it is found as .rnd in the user home * directory. The root home directory may be / or /root, * depending on the system. Wiggle the contents a bit and write * it back so the sequence does not repeat when we next restart. */ - ERR_load_crypto_strings(); - if (rand_file == NULL) { - if ((RAND_file_name(filename, MAXFILENAME)) != NULL) { - rand_file = emalloc(strlen(filename) + 1); - strcpy(rand_file, filename); + if (!RAND_status()) { + if (rand_file == NULL) { + RAND_file_name(filename, sizeof(filename)); + randfile = filename; + } else if (*rand_file != '/') { + snprintf(filename, sizeof(filename), "%s/%s", + keysdir, rand_file); + randfile = filename; + } else + randfile = rand_file; + + if ((bytes = RAND_load_file(randfile, -1)) == 0) { + msyslog(LOG_ERR, + "crypto_setup: random seed file %s missing", + randfile); + exit (-1); } - } else if (*rand_file != '/') { - snprintf(filename, MAXFILENAME, "%s/%s", keysdir, - rand_file); - free(rand_file); - rand_file = emalloc(strlen(filename) + 1); - strcpy(rand_file, filename); + arc4random_buf(&seed, sizeof(l_fp)); + RAND_seed(&seed, sizeof(l_fp)); + RAND_write_file(randfile); + DPRINTF(1, ("crypto_setup: OpenSSL version %lx random seed file %s bytes read %d\n", + SSLeay(), randfile, bytes)); } - if (rand_file == NULL) { - msyslog(LOG_ERR, - "crypto_setup: random seed file not specified"); - exit (-1); - } - if ((bytes = RAND_load_file(rand_file, -1)) == 0) { - msyslog(LOG_ERR, - "crypto_setup: random seed file %s not found\n", - rand_file); - exit (-1); - } - arc4random_buf(&seed, sizeof(l_fp)); - RAND_seed(&seed, sizeof(l_fp)); - RAND_write_file(rand_file); - OpenSSL_add_all_algorithms(); -#ifdef DEBUG - if (debug) - printf( - "crypto_setup: OpenSSL version %lx random seed file %s bytes read %d\n", - SSLeay(), rand_file, bytes); -#endif /* - * Load required host key from file "ntpkey_host_<hostname>". It - * also becomes the default sign key. + * Initialize structures. */ - if (host_file == NULL) { - snprintf(filename, MAXFILENAME, "ntpkey_host_%s", - sys_hostname); - host_file = emalloc(strlen(filename) + 1); - strcpy(host_file, filename); - } - pkey = crypto_key(host_file, &fstamp); - if (pkey == NULL) { + gethostname(hostname, sizeof(hostname)); + if (host_filename != NULL) + strlcpy(hostname, host_filename, sizeof(hostname)); + if (passwd == NULL) + passwd = estrdup(hostname); + memset(&hostval, 0, sizeof(hostval)); + memset(&pubkey, 0, sizeof(pubkey)); + memset(&tai_leap, 0, sizeof(tai_leap)); + + /* + * Load required host key from file "ntpkey_host_<hostname>". If + * no host key file is not found or has invalid password, life + * as we know it ends. The host key also becomes the default + * sign key. + */ + snprintf(filename, sizeof(filename), "ntpkey_host_%s", hostname); + pinfo = crypto_key(filename, passwd, NULL); + if (pinfo == NULL) { msyslog(LOG_ERR, "crypto_setup: host key file %s not found or corrupt", - host_file); + filename); exit (-1); } - host_pkey = pkey; - sign_pkey = pkey; - sstamp = fstamp; - hostval.fstamp = htonl(fstamp); - if (host_pkey->type != EVP_PKEY_RSA) { + if (pinfo->pkey->type != EVP_PKEY_RSA) { msyslog(LOG_ERR, "crypto_setup: host key is not RSA key type"); exit (-1); } - hostval.vallen = htonl(strlen(sys_hostname)); - hostval.ptr = (u_char *)sys_hostname; + host_pkey = pinfo->pkey; + sign_pkey = host_pkey; + hostval.fstamp = htonl(pinfo->fstamp); /* * Construct public key extension field for agreement scheme. @@ -4007,229 +3876,158 @@ crypto_setup(void) ptr = emalloc(len); pubkey.ptr = ptr; i2d_PublicKey(host_pkey, &ptr); - pubkey.vallen = htonl(len); pubkey.fstamp = hostval.fstamp; + pubkey.vallen = htonl(len); /* * Load optional sign key from file "ntpkey_sign_<hostname>". If - * loaded, it becomes the sign key. + * available, it becomes the sign key. */ - if (sign_file == NULL) { - snprintf(filename, MAXFILENAME, "ntpkey_sign_%s", - sys_hostname); - sign_file = emalloc(strlen(filename) + 1); - strcpy(sign_file, filename); - } - pkey = crypto_key(sign_file, &fstamp); - if (pkey != NULL) { - sign_pkey = pkey; - sstamp = fstamp; - } - sign_siglen = EVP_PKEY_size(sign_pkey); + snprintf(filename, sizeof(filename), "ntpkey_sign_%s", hostname); + pinfo = crypto_key(filename, passwd, NULL); + if (pinfo != NULL) + sign_pkey = pinfo->pkey; /* - * Load optional IFF parameters from file - * "ntpkey_iff_<hostname>". - */ - if (iffpar_file == NULL) { - snprintf(filename, MAXFILENAME, "ntpkey_iff_%s", - sys_hostname); - iffpar_file = emalloc(strlen(filename) + 1); - strcpy(iffpar_file, filename); - } - iffpar_pkey = crypto_key(iffpar_file, &if_fstamp); - if (iffpar_pkey != NULL) - crypto_flags |= CRYPTO_FLAG_IFF; - - /* - * Load optional GQ parameters from file "ntpkey_gq_<hostname>". + * Load required certificate from file "ntpkey_cert_<hostname>". */ - if (gqpar_file == NULL) { - snprintf(filename, MAXFILENAME, "ntpkey_gq_%s", - sys_hostname); - gqpar_file = emalloc(strlen(filename) + 1); - strcpy(gqpar_file, filename); + snprintf(filename, sizeof(filename), "ntpkey_cert_%s", hostname); + cinfo = crypto_cert(filename); + if (cinfo == NULL) { + msyslog(LOG_ERR, + "crypto_setup: certificate file %s not found or corrupt", + filename); + exit (-1); } - gqpar_pkey = crypto_key(gqpar_file, &gq_fstamp); - if (gqpar_pkey != NULL) - crypto_flags |= CRYPTO_FLAG_GQ; + cert_host = cinfo; + sign_digest = cinfo->digest; + sign_siglen = EVP_PKEY_size(sign_pkey); + if (cinfo->flags & CERT_PRIV) + crypto_flags |= CRYPTO_FLAG_PRIV; /* - * Load optional MV parameters from file "ntpkey_mv_<hostname>". + * The certificate must be self-signed. */ - if (mvpar_file == NULL) { - snprintf(filename, MAXFILENAME, "ntpkey_mv_%s", - sys_hostname); - mvpar_file = emalloc(strlen(filename) + 1); - strcpy(mvpar_file, filename); + if (strcmp(cinfo->subject, cinfo->issuer) != 0) { + msyslog(LOG_ERR, + "crypto_setup: certificate %s is not self-signed", + filename); + exit (-1); } - mvpar_pkey = crypto_key(mvpar_file, &mv_fstamp); - if (mvpar_pkey != NULL) - crypto_flags |= CRYPTO_FLAG_MV; + hostval.ptr = estrdup(cinfo->subject); + hostval.vallen = htonl(strlen(cinfo->subject)); + sys_hostname = hostval.ptr; + ptr = (u_char *)strchr(sys_hostname, '@'); + if (ptr != NULL) + sys_groupname = estrdup((char *)++ptr); + if (ident_filename != NULL) + strlcpy(hostname, ident_filename, sizeof(hostname)); /* - * Load required certificate from file "ntpkey_cert_<hostname>". + * Load optional IFF parameters from file + * "ntpkey_iffkey_<hostname>". */ - if (cert_file == NULL) { - snprintf(filename, MAXFILENAME, "ntpkey_cert_%s", - sys_hostname); - cert_file = emalloc(strlen(filename) + 1); - strcpy(cert_file, filename); - } - if ((cinfo = crypto_cert(cert_file)) == NULL) { - msyslog(LOG_ERR, - "certificate file %s not found or corrupt", - cert_file); - exit (-1); - } + snprintf(filename, sizeof(filename), "ntpkey_iffkey_%s", + hostname); + iffkey_info = crypto_key(filename, passwd, NULL); + if (iffkey_info != NULL) + crypto_flags |= CRYPTO_FLAG_IFF; /* - * The subject name must be the same as the host name, unless - * the certificate is private, in which case it may have come - * from another host. + * Load optional GQ parameters from file + * "ntpkey_gqkey_<hostname>". */ - if (!(cinfo->flags & CERT_PRIV) && strcmp(cinfo->subject, - sys_hostname) != 0) { - msyslog(LOG_ERR, - "crypto_setup: certificate %s not for this host", - cert_file); - cert_free(cinfo); - exit (-1); - } + snprintf(filename, sizeof(filename), "ntpkey_gqkey_%s", + hostname); + gqkey_info = crypto_key(filename, passwd, NULL); + if (gqkey_info != NULL) + crypto_flags |= CRYPTO_FLAG_GQ; /* - * It the certificate is trusted, the subject must be the same - * as the issuer, in other words it must be self signed. + * Load optional MV parameters from file + * "ntpkey_mvkey_<hostname>". */ - if (cinfo->flags & CERT_TRUST && strcmp(cinfo->subject, - cinfo->issuer) != 0) { - if (cert_valid(cinfo, sign_pkey) != XEVNT_OK) { - msyslog(LOG_ERR, - "crypto_setup: certificate %s is trusted, but not self signed.", - cert_file); - cert_free(cinfo); - exit (-1); - } - } - sign_digest = cinfo->digest; - if (cinfo->flags & CERT_PRIV) - crypto_flags |= CRYPTO_FLAG_PRIV; - crypto_flags |= cinfo->nid << 16; + snprintf(filename, sizeof(filename), "ntpkey_mvkey_%s", + hostname); + mvkey_info = crypto_key(filename, passwd, NULL); + if (mvkey_info != NULL) + crypto_flags |= CRYPTO_FLAG_MV; /* - * Load optional leapseconds table from file "ntpkey_leap". If - * the file is missing or defective, the values can later be - * retrieved from a server. + * We met the enemy and he is us. Now strike up the dance. */ - if (leap_file == NULL) - leap_file = "ntpkey_leap"; - crypto_tai(leap_file); -#ifdef DEBUG - if (debug) - printf( - "crypto_setup: flags 0x%x host %s signature %s\n", - crypto_flags, sys_hostname, OBJ_nid2ln(cinfo->nid)); -#endif + crypto_flags |= CRYPTO_FLAG_ENAB | (cinfo->nid << 16); + snprintf(statstr, sizeof(statstr), "setup 0x%x host %s %s", + crypto_flags, hostname, OBJ_nid2ln(cinfo->nid)); + record_crypto_stats(NULL, statstr); + DPRINTF(1, ("crypto_setup: %s\n", statstr)); } /* - * crypto_config - configure data from crypto configuration command. + * crypto_config - configure data from the crypto command. */ void crypto_config( int item, /* configuration item */ - char *cp /* file name */ + char *cp /* item name */ ) { - switch (item) { + int nid; - /* - * Set random seed file name. - */ - case CRYPTO_CONF_RAND: - rand_file = emalloc(strlen(cp) + 1); - strcpy(rand_file, cp); - break; + DPRINTF(1, ("crypto_config: item %d %s\n", item, cp)); - /* - * Set private key password. - */ - case CRYPTO_CONF_PW: - passwd = emalloc(strlen(cp) + 1); - strcpy(passwd, cp); - break; + switch (item) { /* - * Set host file name. + * Set host name (host). */ case CRYPTO_CONF_PRIV: - host_file = emalloc(strlen(cp) + 1); - strcpy(host_file, cp); + if (NULL != host_filename) + free(host_filename); + host_filename = estrdup(cp); break; /* - * Set sign key file name. + * Set group name (ident). */ - case CRYPTO_CONF_SIGN: - sign_file = emalloc(strlen(cp) + 1); - strcpy(sign_file, cp); - break; - - /* - * Set iff parameters file name. - */ - case CRYPTO_CONF_IFFPAR: - iffpar_file = emalloc(strlen(cp) + 1); - strcpy(iffpar_file, cp); - break; - - /* - * Set gq parameters file name. - */ - case CRYPTO_CONF_GQPAR: - gqpar_file = emalloc(strlen(cp) + 1); - strcpy(gqpar_file, cp); - break; - - /* - * Set mv parameters file name. - */ - case CRYPTO_CONF_MVPAR: - mvpar_file = emalloc(strlen(cp) + 1); - strcpy(mvpar_file, cp); + case CRYPTO_CONF_IDENT: + if (NULL != ident_filename) + free(ident_filename); + ident_filename = estrdup(cp); break; /* - * Set identity scheme. + * Set private key password (pw). */ - case CRYPTO_CONF_IDENT: - if (!strcasecmp(cp, "iff")) - ident_scheme |= CRYPTO_FLAG_IFF; - else if (!strcasecmp(cp, "gq")) - ident_scheme |= CRYPTO_FLAG_GQ; - else if (!strcasecmp(cp, "mv")) - ident_scheme |= CRYPTO_FLAG_MV; + case CRYPTO_CONF_PW: + if (NULL != passwd) + free(passwd); + passwd = estrdup(cp); break; /* - * Set certificate file name. + * Set random seed file name (randfile). */ - case CRYPTO_CONF_CERT: - cert_file = emalloc(strlen(cp) + 1); - strcpy(cert_file, cp); + case CRYPTO_CONF_RAND: + if (NULL != rand_file) + free(rand_file); + rand_file = estrdup(cp); break; /* - * Set leapseconds file name. + * Set message digest NID. */ - case CRYPTO_CONF_LEAP: - leap_file = emalloc(strlen(cp) + 1); - strcpy(leap_file, cp); + case CRYPTO_CONF_NID: + nid = OBJ_sn2nid(cp); + if (nid == 0) + msyslog(LOG_ERR, + "crypto_config: invalid digest name %s", cp); + else + crypto_nid = nid; break; } - crypto_flags |= CRYPTO_FLAG_ENAB; } -# else +# else /* !AUTOKEY follows */ int ntp_crypto_bs_pubkey; -# endif /* OPENSSL */ +# endif /* !AUTOKEY */ |