/contrib/ntp/ntpd/ntp_crypto.c
https://bitbucket.org/freebsd/freebsd-head/ · C · 4189 lines · 2414 code · 326 blank · 1449 comment · 578 complexity · 24628f797239e75d9f4988848ef9a38c MD5 · raw file
Large files are truncated click here to view the full file
- /*
- * ntp_crypto.c - NTP version 4 public key routines
- */
- #ifdef HAVE_CONFIG_H
- #include <config.h>
- #endif
- #ifdef OPENSSL
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/param.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include "ntpd.h"
- #include "ntp_stdlib.h"
- #include "ntp_unixtime.h"
- #include "ntp_string.h"
- #include <ntp_random.h>
- #include "openssl/asn1_mac.h"
- #include "openssl/bn.h"
- #include "openssl/err.h"
- #include "openssl/evp.h"
- #include "openssl/pem.h"
- #include "openssl/rand.h"
- #include "openssl/x509v3.h"
- #ifdef KERNEL_PLL
- #include "ntp_syscall.h"
- #endif /* KERNEL_PLL */
- /*
- * Extension field message format
- *
- * These are always signed and saved before sending in network byte
- * order. They must be converted to and from host byte order for
- * processing.
- *
- * +-------+-------+
- * | op | len | <- extension pointer
- * +-------+-------+
- * | assocID |
- * +---------------+
- * | timestamp | <- value pointer
- * +---------------+
- * | filestamp |
- * +---------------+
- * | value len |
- * +---------------+
- * | |
- * = value =
- * | |
- * +---------------+
- * | signature len |
- * +---------------+
- * | |
- * = signature =
- * | |
- * +---------------+
- *
- * The CRYPTO_RESP bit is set to 0 for requests, 1 for responses.
- * Requests carry the association ID of the receiver; responses carry
- * the association ID of the sender. Some messages include only the
- * operation/length and association ID words and so have length 8
- * octets. Ohers include the value structure and associated value and
- * signature fields. These messages include the timestamp, filestamp,
- * value and signature words and so have length at least 24 octets. The
- * signature and/or value fields can be empty, in which case the
- * respective length words are zero. An empty value with nonempty
- * signature is syntactically valid, but semantically questionable.
- *
- * The filestamp represents the time when a cryptographic data file such
- * as a public/private key pair is created. It follows every reference
- * depending on that file and serves as a means to obsolete earlier data
- * of the same type. The timestamp represents the time when the
- * cryptographic data of the message were last signed. Creation of a
- * cryptographic data file or signing a message can occur only when the
- * 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.
- */
- /*
- * Cryptodefines
- */
- #define TAI_1972 10 /* initial TAI offset (s) */
- #define MAX_LEAP 100 /* max UTC leapseconds (s) */
- #define VALUE_LEN (6 * 4) /* min response field length */
- #define YEAR (60 * 60 * 24 * 365) /* seconds in year */
- /*
- * Global cryptodata in host byte order
- */
- u_int32 crypto_flags = 0x0; /* status word */
- /*
- * Global cryptodata in network byte order
- */
- struct cert_info *cinfo = NULL; /* certificate info/value */
- 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 */
- /*
- * Private cryptodata in host byte order
- */
- static char *passwd = NULL; /* private key password */
- static EVP_PKEY *host_pkey = NULL; /* host key */
- 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((struct exten *, struct value *,
- keyid_t *));
- 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 *));
- #ifdef SYS_WINNT
- int
- readlink(char * link, char * file, int len) {
- return (-1);
- }
- #endif
- /*
- * session_key - generate session key
- *
- * This routine generates a session key from the source address,
- * destination address, key ID and private value. The value of the
- * 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
- */
- keyid_t
- session_key(
- struct sockaddr_storage *srcadr, /* source address */
- struct sockaddr_storage *dstadr, /* destination address */
- keyid_t keyno, /* key ID */
- keyid_t private, /* private value */
- u_long lifetime /* key lifetime */
- )
- {
- EVP_MD_CTX ctx; /* message digest context */
- u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
- keyid_t keyid; /* key identifer */
- u_int32 header[10]; /* data in network byte order */
- u_int hdlen, len;
- if (!dstadr)
- return 0;
-
- /*
- * Generate the session key and key ID. If the lifetime is
- * greater than zero, install the key and call it trusted.
- */
- hdlen = 0;
- switch(srcadr->ss_family) {
- case AF_INET:
- header[0] = ((struct sockaddr_in *)srcadr)->sin_addr.s_addr;
- header[1] = ((struct sockaddr_in *)dstadr)->sin_addr.s_addr;
- header[2] = htonl(keyno);
- header[3] = htonl(private);
- hdlen = 4 * sizeof(u_int32);
- break;
- case AF_INET6:
- memcpy(&header[0], &GET_INADDR6(*srcadr),
- sizeof(struct in6_addr));
- memcpy(&header[4], &GET_INADDR6(*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_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);
- authtrust(keyno, lifetime);
- }
- #ifdef DEBUG
- if (debug > 1)
- printf(
- "session_key: %s > %s %08x %08x hash %08x life %lu\n",
- stoa(srcadr), stoa(dstadr), keyno,
- private, keyid, lifetime);
- #endif
- return (keyid);
- }
- /*
- * make_keylist - generate key list
- *
- * Returns
- * XEVNT_OK success
- * XEVNT_PER host certificate expired
- *
- * This routine constructs a pseudo-random sequence by repeatedly
- * hashing the session key starting from a given source address,
- * destination address, private value and the next key ID of the
- * preceeding session key. The last entry on the list is saved along
- * with its sequence number and public signature.
- */
- int
- make_keylist(
- struct peer *peer, /* peer structure pointer */
- struct interface *dstadr /* interface */
- )
- {
- EVP_MD_CTX ctx; /* signature context */
- tstamp_t tstamp; /* NTP timestamp */
- struct autokey *ap; /* autokey pointer */
- struct value *vp; /* value pointer */
- keyid_t keyid = 0; /* next key ID */
- keyid_t cookie; /* private value */
- u_long lifetime;
- u_int len, mpoll;
- int i;
- if (!dstadr)
- return XEVNT_OK;
-
- /*
- * Allocate the key list if necessary.
- */
- tstamp = crypto_time();
- if (peer->keylist == NULL)
- peer->keylist = emalloc(sizeof(keyid_t) *
- NTP_MAXSESSION);
- /*
- * 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);
- if (authhavekey(keyid))
- continue;
- break;
- }
- /*
- * Generate up to NTP_MAXSESSION session keys. Stop if the
- * next one would not be unique or not a session key ID or if
- * it would expire before the next poll. The private value
- * included in the hash is zero if broadcast mode, the peer
- * 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);
- if (peer->hmode == MODE_BROADCAST)
- cookie = 0;
- else
- cookie = peer->pcookie;
- for (i = 0; i < NTP_MAXSESSION; i++) {
- peer->keylist[i] = keyid;
- peer->keynumber = i;
- keyid = session_key(&dstadr->sin, &peer->srcadr, keyid,
- cookie, lifetime);
- lifetime -= mpoll;
- if (auth_havekey(keyid) || keyid <= NTP_MAXKEY ||
- lifetime <= mpoll)
- break;
- }
- /*
- * Save the last session key ID, sequence number and timestamp,
- * then sign these values for later retrieval by the clients. Be
- * careful not to use invalid key media. Use the public values
- * timestamp as filestamp.
- */
- vp = &peer->sndval;
- if (vp->ptr == NULL)
- vp->ptr = emalloc(sizeof(struct autokey));
- ap = (struct autokey *)vp->ptr;
- ap->seq = htonl(peer->keynumber);
- ap->key = htonl(keyid);
- vp->tstamp = htonl(tstamp);
- vp->fstamp = hostval.tstamp;
- 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))
- vp->siglen = htonl(len);
- else
- msyslog(LOG_ERR, "make_keys %s\n",
- ERR_error_string(ERR_get_error(), NULL));
- 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
- return (XEVNT_OK);
- }
- /*
- * crypto_recv - parse extension fields
- *
- * This routine is called when the packet has been matched to an
- * association and passed sanity, format and MAC checks. We believe the
- * extension field values only if the field has proper format and
- * length, the timestamp and filestamp are valid and the signature has
- * 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.
- */
- int
- crypto_recv(
- struct peer *peer, /* peer structure pointer */
- struct recvbuf *rbufp /* packet buffer pointer */
- )
- {
- const EVP_MD *dp; /* message digest algorithm */
- u_int32 *pkt; /* receive packet pointer */
- struct autokey *ap, *bp; /* autokey pointer */
- struct exten *ep, *fp; /* extension pointers */
- 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 */
- u_int vallen = 0; /* value length */
- X509 *cert; /* X509 certificate */
- char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
- keyid_t cookie; /* crumbles */
- int hismode; /* packet mode */
- int rval = XEVNT_OK;
- u_char *ptr;
- u_int32 temp32;
- /*
- * Initialize. Note that the packet has already been checked for
- * valid format and extension field lengths. First extract the
- * field length, command code and association ID in host byte
- * order. These are used with all commands and modes. Then check
- * the version number, which must be 2, and length, which must
- * be at least 8 for requests and VALUE_LEN (24) for responses.
- * Packets that fail either test sink without a trace. The
- * association ID is saved only if nonzero.
- */
- authlen = LEN_PKT_NOMAC;
- hismode = (int)PKT_MODE((&rbufp->recv_pkt)->li_vn_mode);
- while ((has_mac = rbufp->recv_length - authlen) > 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]);
- rval = XEVNT_OK;
- #ifdef DEBUG
- if (debug)
- printf(
- "crypto_recv: flags 0x%x ext offset %d len %u code 0x%x assocID %d\n",
- peer->crypto, authlen, len, code >> 16,
- associd);
- #endif
- /*
- * Check version number and field length. If bad,
- * quietly ignore the packet.
- */
- if (((code >> 24) & 0x3f) != CRYPTO_VN || len < 8) {
- sys_unknownversion++;
- 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);
- }
- switch (code) {
- /*
- * Install status word, host name, signature scheme and
- * association ID. In OpenSSL the signature algorithm is
- * bound to the digest algorithm, so the NID completely
- * defines the signature scheme. Note the request and
- * response are identical, but neither is validated by
- * signature. The request is processed here only in
- * symmetric modes. The server name field might be
- * useful to implement access controls in future.
- */
- 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 (peer->crypto) {
- rval = XEVNT_ERR;
- break;
- }
- fp = emalloc(len);
- memcpy(fp, ep, len);
- temp32 = CRYPTO_RESP;
- fp->opcode |= htonl(temp32);
- peer->cmmd = fp;
- /* fall through */
- case CRYPTO_ASSOC | CRYPTO_RESP:
- /*
- * Discard the message if it has already been
- * stored or the message has been amputated.
- */
- if (peer->crypto)
- break;
- if (vallen == 0 || vallen > MAXHOSTNAME ||
- len < VALUE_LEN + vallen) {
- rval = XEVNT_LEN;
- break;
- }
- /*
- * 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.
- */
- #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;
- }
- /*
- * Otherwise, the identity scheme(s) are those
- * that both client and server support.
- */
- fstamp = temp32 | (fstamp & ~CRYPTO_FLAG_MASK);
- /*
- * Discard the message if the signature digest
- * NID is not supported.
- */
- temp32 = (fstamp >> 16) & 0xffff;
- dp =
- (const EVP_MD *)EVP_get_digestbynid(temp32);
- if (dp == NULL) {
- rval = XEVNT_MD;
- break;
- }
- /*
- * Save status word, host name and message
- * digest/signature type.
- */
- peer->crypto = fstamp;
- peer->digest = dp;
- 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));
- record_crypto_stats(&peer->srcadr, statstr);
- #ifdef DEBUG
- if (debug)
- printf("crypto_recv: %s\n", statstr);
- #endif
- break;
- /*
- * Decode X509 certificate in ASN.1 format and extract
- * the data containing, among other things, subject
- * name and public key. In the default identification
- * scheme, the certificate trail is followed to a self
- * signed trusted certificate.
- */
- case CRYPTO_CERT | CRYPTO_RESP:
- /*
- * Discard the message if invalid.
- */
- if ((rval = crypto_verify(ep, NULL, peer)) !=
- XEVNT_OK)
- break;
- /*
- * Scan the certificate list to delete old
- * versions and link the newest version first on
- * the list.
- */
- if ((rval = cert_install(ep, peer)) != 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
- * the first certificate received. However, note
- * that this certificate might not be signed by
- * the server, so we can't check the
- * signature/digest NID.
- */
- if (peer->pkey == NULL) {
- ptr = (u_char *)cinfo->cert.ptr;
- cert = d2i_X509(NULL, &ptr,
- ntohl(cinfo->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,
- OBJ_nid2ln(temp32), temp32,
- ntohl(ep->fstamp));
- record_crypto_stats(&peer->srcadr, statstr);
- #ifdef DEBUG
- if (debug)
- printf("crypto_recv: %s\n", statstr);
- #endif
- 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
- * server contain the same secret group key.
- */
- case CRYPTO_IFF | CRYPTO_RESP:
- /*
- * 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;
- /*
- * If the the challenge matches the response,
- * the certificate public key, as well as the
- * server public key, signatyre 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.
- */
- if ((rval = crypto_iff(ep, peer)) != XEVNT_OK)
- break;
- peer->crypto |= CRYPTO_FLAG_VRFY |
- CRYPTO_FLAG_PROV;
- peer->flash &= ~TEST8;
- snprintf(statstr, NTP_MAXSTRLEN, "iff fs %u",
- ntohl(ep->fstamp));
- record_crypto_stats(&peer->srcadr, statstr);
- #ifdef DEBUG
- if (debug)
- printf("crypto_recv: %s\n", statstr);
- #endif
- break;
- /*
- * Guillou-Quisquater (GQ) identity scheme. This scheme
- * is designed for use with public certificates carrying
- * the GQ public key in an extension field. 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 group key and the server has the matching GQ
- * private key.
- */
- case CRYPTO_GQ | CRYPTO_RESP:
- /*
- * 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;
- /*
- * If the the challenge matches the response,
- * the certificate public key, as well as the
- * server public key, signatyre 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.
- */
- if ((rval = crypto_gq(ep, peer)) != XEVNT_OK)
- break;
- peer->crypto |= CRYPTO_FLAG_VRFY |
- CRYPTO_FLAG_PROV;
- peer->flash &= ~TEST8;
- snprintf(statstr, NTP_MAXSTRLEN, "gq fs %u",
- ntohl(ep->fstamp));
- record_crypto_stats(&peer->srcadr, statstr);
- #ifdef DEBUG
- if (debug)
- printf("crypto_recv: %s\n", statstr);
- #endif
- break;
- /*
- * MV
- */
- case CRYPTO_MV | CRYPTO_RESP:
- /*
- * 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;
- /*
- * If the the challenge matches the response,
- * the certificate public key, as well as the
- * server public key, signatyre 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.
- */
- if ((rval = crypto_mv(ep, peer)) != XEVNT_OK)
- break;
- peer->crypto |= CRYPTO_FLAG_VRFY |
- CRYPTO_FLAG_PROV;
- peer->flash &= ~TEST8;
- snprintf(statstr, NTP_MAXSTRLEN, "mv fs %u",
- ntohl(ep->fstamp));
- record_crypto_stats(&peer->srcadr, statstr);
- #ifdef DEBUG
- if (debug)
- printf("crypto_recv: %s\n", statstr);
- #endif
- 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
- * cookie bit is set, the working cookie is the EXOR of
- * the current and new values.
- */
- case CRYPTO_COOK | CRYPTO_RESP:
- /*
- * Discard the message if invalid or identity
- * not confirmed 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;
- /*
- * Decrypt the cookie, hunting all the time for
- * errors.
- */
- if (vallen == (u_int) EVP_PKEY_size(host_pkey)) {
- RSA_private_decrypt(vallen,
- (u_char *)ep->pkt,
- (u_char *)&temp32,
- host_pkey->pkey.rsa,
- RSA_PKCS1_OAEP_PADDING);
- cookie = ntohl(temp32);
- } else {
- rval = XEVNT_CKY;
- break;
- }
- /*
- * Install cookie values and light the cookie
- * bit. If this is not broadcast client mode, we
- * 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;
- 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->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;
- /*
- * Install autokey values in broadcast client and
- * symmetric modes. We have to do this every time the
- * sever/peer cookie changes or a new keylist is
- * rolled. Ordinarily, this is automatic as this message
- * is piggybacked on the first NTP packet sent upon
- * either of these events. Note that a broadcast client
- * or symmetric peer can receive this response without a
- * matching request.
- */
- 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.
- */
- if (!(peer->crypto & CRYPTO_FLAG_VRFY)) {
- rval = XEVNT_ERR;
- break;
- }
- if ((rval = crypto_verify(ep, &peer->recval,
- peer)) != XEVNT_OK)
- break;
- /*
- * Install autokey values and light the
- * autokey bit. This is not hard.
- */
- if (peer->recval.ptr == NULL)
- peer->recval.ptr =
- emalloc(sizeof(struct autokey));
- bp = (struct autokey *)peer->recval.ptr;
- peer->recval.tstamp = ep->tstamp;
- peer->recval.fstamp = ep->fstamp;
- ap = (struct autokey *)ep->pkt;
- bp->seq = ntohl(ap->seq);
- bp->key = ntohl(ap->key);
- peer->pkeyid = bp->key;
- peer->crypto |= CRYPTO_FLAG_AUTO;
- peer->flash &= ~TEST8;
- snprintf(statstr, NTP_MAXSTRLEN,
- "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
- break;
-
- /*
- * X509 certificate sign response. Validate the
- * certificate signed by the server and install. Later
- * this can be provided to clients of this server in
- * lieu of the self signed certificate in order to
- * validate the public key.
- */
- case CRYPTO_SIGN | CRYPTO_RESP:
- /*
- * Discard the message if invalid or not
- * proventic.
- */
- if (!(peer->crypto & CRYPTO_FLAG_PROV)) {
- rval = XEVNT_ERR;
- break;
- }
- if ((rval = crypto_verify(ep, NULL, peer)) !=
- XEVNT_OK)
- break;
- /*
- * Scan the certificate list to delete old
- * versions and link the newest version first on
- * the list.
- */
- if ((rval = cert_install(ep, peer)) != XEVNT_OK)
- 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,
- OBJ_nid2ln(temp32), temp32,
- ntohl(ep->fstamp));
- record_crypto_stats(&peer->srcadr, statstr);
- #ifdef DEBUG
- if (debug)
- printf("crypto_recv: %s\n", statstr);
- #endif
- 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.
- */
- case CRYPTO_TAI:
- /*
- * Discard the message if invalid.
- */
- if ((rval = crypto_verify(ep, NULL, peer)) !=
- XEVNT_OK)
- 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.
- */
- 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;
- 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));
- record_crypto_stats(&peer->srcadr, statstr);
- #ifdef DEBUG
- if (debug)
- printf("crypto_recv: %s\n", statstr);
- #endif
- 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.
- */
- case CRYPTO_CERT:
- case CRYPTO_IFF:
- case CRYPTO_GQ:
- case CRYPTO_MV:
- case CRYPTO_SIGN:
- if (len < VALUE_LEN) {
- rval = XEVNT_LEN;
- break;
- }
- /* 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.
- */
- default:
- if (code & (CRYPTO_RESP | CRYPTO_ERROR)) {
- rval = XEVNT_ERR;
- } else if ((rval = crypto_verify(ep, NULL,
- peer)) == XEVNT_OK) {
- 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.
- */
- if (rval > XEVNT_TSP) {
- snprintf(statstr, NTP_MAXSTRLEN,
- "error %x opcode %x ts %u fs %u", rval,
- code, tstamp, fstamp);
- 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;
- }
- authlen += len;
- }
- return (rval);
- }
- /*
- * crypto_xmit - construct extension fields
- *
- * This routine is called both when an association is configured and
- * when one is not. The only case where this matters is to retrieve the
- * autokey information, in which case the caller has to provide the
- * association ID to match the association.
- *
- * Returns length of extension field.
- */
- int
- crypto_xmit(
- struct pkt *xpkt, /* transmit packet pointer */
- struct sockaddr_storage *srcadr_sin, /* active runway */
- int start, /* offset to extension field */
- struct exten *ep, /* extension pointer */
- keyid_t cookie /* session cookie */
- )
- {
- 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;
- u_int vallen;
- u_int len;
- struct value vtemp;
- associd_t associd;
- int rval;
- keyid_t tcookie;
- /*
- * Generate the requested extension field request code, length
- * and association ID. If this is a response and the host is not
- * synchronized, light the error bit and go home.
- */
- pkt = (u_int32 *)xpkt + start / 4;
- fp = (struct exten *)pkt;
- opcode = ntohl(ep->opcode);
- associd = (associd_t) ntohl(ep->associd);
- fp->associd = htonl(associd);
- len = 8;
- rval = XEVNT_OK;
- tstamp = crypto_time();
- switch (opcode & 0xffff0000) {
- /*
- * Send association request and response with status word and
- * host name. Note, this message is not signed and the filestamp
- * contains only the status word.
- */
- case CRYPTO_ASSOC | CRYPTO_RESP:
- len += crypto_send(fp, &hostval);
- 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.
- */
- case CRYPTO_CERT:
- memset(&vtemp, 0, sizeof(vtemp));
- vtemp.tstamp = ep->tstamp;
- vtemp.fstamp = ep->fstamp;
- vtemp.vallen = ep->vallen;
- vtemp.ptr = (u_char *)ep->pkt;
- len += crypto_send(fp, &vtemp);
- 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.
- */
- case CRYPTO_SIGN:
- case CRYPTO_CERT | CRYPTO_RESP:
- vallen = ntohl(ep->vallen);
- if (vallen == 8) {
- strcpy(certname, sys_hostname);
- } else if (vallen == 0 || vallen > MAXHOSTNAME) {
- 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.
- */
- xp = NULL;
- for (cp = cinfo; cp != NULL; cp = cp->link) {
- if (cp->flags & CERT_PRIV)
- 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;
- }
- }
- }
- /*
- * 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.
- *
- * Note 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
- * allows strong checking for signature masquerade.
- */
- 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);
- break;
- /*
- * Send challenge in Schnorr (IFF) identity scheme.
- */
- case CRYPTO_IFF:
- if ((peer = findpeerbyassoc(ep->pkt[0])) == NULL) {
- rval = XEVNT_ERR;
- break;
- }
- if ((rval = crypto_alice(peer, &vtemp)) == XEVNT_OK) {
- len += crypto_send(fp, &vtemp);
- value_free(&vtemp);
- }
- break;
- /*
- * Send response in Schnorr (IFF) identity scheme.
- */
- case CRYPTO_IFF | CRYPTO_RESP:
- if ((rval = crypto_bob(ep, &vtemp)) == XEVNT_OK) {
- len += crypto_send(fp, &vtemp);
- value_free(&vtemp);
- }
- break;
- /*
- * Send challenge in Guillou-Quisquater (GQ) identity scheme.
- */
- case CRYPTO_GQ:
- if ((peer = findpeerbyassoc(ep->pkt[0])) == NULL) {
- rval = XEVNT_ERR;
- break;
- }
- if ((rval = crypto_alice2(peer, &vtemp)) == XEVNT_OK) {
- len += crypto_send(fp, &vtemp);
- value_free(&vtemp);
- }
- break;
- /*
- * Send response in Guillou-Quisquater (GQ) identity scheme.
- */
- case CRYPTO_GQ | CRYPTO_RESP:
- if ((rval = crypto_bob2(ep, &vtemp)) == XEVNT_OK) {
- len += crypto_send(fp, &vtemp);
- value_free(&vtemp);
- }
- break;
- /*
- * Send challenge in MV identity scheme.
- */
- case CRYPTO_MV:
- if ((peer = findpeerbyassoc(ep->pkt[0])) == NULL) {
- rval = XEVNT_ERR;
- break;
- }
- if ((rval = crypto_alice3(peer, &vtemp)) == XEVNT_OK) {
- len += crypto_send(fp, &vtemp);
- value_free(&vtemp);
- }
- break;
- /*
- * Send response in MV identity scheme.
- */
- case CRYPTO_MV | CRYPTO_RESP:
- if ((rval = crypto_bob3(ep, &vtemp)) == XEVNT_OK) {
- len += crypto_send(fp, &vtemp);
- value_free(&vtemp);
- }
- break;
- /*
- * Send certificate sign response. The integrity of the request
- * certificate has already been verified on the receive side.
- * Sign the response using the local server key. Use the
- * filestamp from the request and use the timestamp as the
- * current time. Light the error bit if the certificate is
- * 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);
- break;
- /*
- * Send public key and signature. Use the values from the public
- * key.
- */
- case CRYPTO_COOK:
- len += crypto_send(fp, &pubkey);
- break;
- /*
- * Encrypt and send cookie and signature. Light the error bit if
- * anything goes wrong.
- */
- case CRYPTO_COOK | CRYPTO_RESP:
- if ((opcode & 0xffff) < VALUE_LEN) {
- rval = XEVNT_LEN;
- break;
- }
- if (PKT_MODE(xpkt->li_vn_mode) == MODE_SERVER) {
- tcookie = cookie;
- } else {
- if ((peer = findpeerbyassoc(associd)) == NULL) {
- rval = XEVNT_ERR;
- break;
- }
- tcookie = peer->pcookie;
- }
- if ((rval = crypto_encrypt(ep, &vtemp, &tcookie)) ==
- XEVNT_OK)
- len += crypto_send(fp, &vtemp);
- value_free(&vtemp);
- break;
- /*
- * Find peer and send autokey data and signature in broadcast
- * server and symmetric modes. Use the values in the autokey
- * structure. If no association is found, either the server has
- * restarted with new associations or some perp has replayed an
- * old message, in which case light the error bit.
- */
- case CRYPTO_AUTO | CRYPTO_RESP:
- if ((peer = findpeerbyassoc(associd)) == NULL) {
- rval = XEVNT_ERR;
- break;
- }
- peer->flags &= ~FLAG_ASSOC;
- len += crypto_send(fp, &peer->sndval);
- break;
- /*
- * Send leapseconds table 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);
- break;
- /*
- * Default - Fall through for requests; for unknown responses,
- * flag as error.
- */
- default:
- if (opcode & CRYPTO_RESP)
- rval = XEVNT_ERR;
- }
- /*
- * In case of error, flame the log. If a request, toss the
- * 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);
- record_crypto_stats(srcadr_sin, statstr);
- report_event(rval, NULL);
- #ifdef DEBUG
- if (debug)
- printf("crypto_xmit: %s\n", statstr);
- #endif
- 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
- return (len);
- }
- /*
- * crypto_verify - parse and verify the extension field and value
- *
- * Returns
- * XEVNT_OK success
- * XEVNT_LEN bad field format or length
- * XEVNT_TSP bad timestamp
- * XEVNT_FSP bad filestamp
- * XEVNT_PUB bad or missing public key
- * XEVNT_SGL bad signature length
- * XEVNT_SIG signature not verified
- * XEVNT_ERR protocol error
- */
- static int
- crypto_verify(
- struct exten *ep, /* extension pointer */
- struct value *vp, /* value pointer */
- struct peer *peer /* peer structure pointer */
- )
- {
- EVP_PKEY *pkey; /* server public key */
- EVP_MD_CTX ctx; /* signature context */
- tstamp_t tstamp, tstamp1 = 0; /* timestamp */
- tstamp_t fstamp, fstamp1 = 0; /* filestamp */
- u_int vallen; /* value length */
- u_int siglen; /* signature length */
- u_int opcode, len;
- 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.
- */
- 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.
- */
- if (opcode & CRYPTO_ERROR)
- return (XEVNT_ERR);
- if (opcode & CRYPTO_RESP) {
- if (len < VALUE_LEN)
- return (XEVNT_LEN);
- } else {
- if (len < VALUE_LEN)
- return (XEVNT_OK);
- }
- /*
- * 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.
- */
- vallen = ntohl(ep->vallen);
- i = (vallen + 3) / 4;
- siglen = ntohl(ep->pkt[i++]);
- if (len < VALUE_LEN + ((vallen + 3) / 4) * 4 + ((siglen + 3) /
- 4) * 4)
- 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
- * 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.
- */
- tstamp = ntohl(ep->tstamp);
- fstamp = ntohl(ep->fstamp);
- if (tstamp == 0)
- return (XEVNT_OK);
- if (tstamp < fstamp)
- return (XEVNT_TSP);
- 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 ((tstamp < fstamp1 || fstamp < fstamp1))
- return (XEVNT_FSP);
- }
- /*
- * Check for valid signature length, public key and digest
- * algorithm.
- */
- if (crypto_flags & peer->crypto & CRYPTO_FLAG_PRIV)
- pkey = sign_pkey;
- else
- pkey = peer->pkey;
- if (siglen == 0 || pkey == NULL || peer->digest == NULL)
- return (XEVNT_OK);
- if (siglen != (u_int)EVP_PKEY_size(pkey))
- return (XEVNT_SGL);
- /*
- * 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.
- */
- EVP_VerifyInit(&ctx, peer->digest);
- EVP_VerifyUpdate(&ctx, (u_char *)&ep->tstamp, vallen + 12);
- if (EVP_VerifyFinal(&ctx, (u_char *)&ep->pkt[i], siglen, pkey) <= 0)
- return (XEVNT_SIG);
- 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);
- }
- /*
- * crypto_encrypt - construct encrypted cookie and signature from
- * extension field and cookie
- *
- * Returns
- * XEVNT_OK success
- * XEVNT_PUB bad or missing public key
- * XEVNT_CKY bad or missing cookie
- * XEVNT_PER host certificate expired
- */
- static int
- crypto_encrypt(
- struct exten *ep, /* extension pointer */
- struct value *vp, /* value pointer */
- keyid_t *cookie /* server cookie */
- )
- {
- EVP_PKEY *pkey; /* public key */
- EVP_MD_CTX ctx; /* signature context */
- tstamp_t tstamp; /* NTP timestamp */
- u_int32 temp32;
- u_int len;
- u_char *ptr;
- /*
- * Extract the public key from the request.
- */
- len = ntohl(ep->vallen);
- ptr = (u_char *)ep->pkt;
- pkey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &ptr, len);
- if (pkey == NULL) {
- msyslog(LOG_ERR, "crypto_encrypt %s\n",
- ERR_error_string(ERR_get_error(), NULL));
- return (XEVNT_PUB);
- }
- /*
- * Encrypt the cookie, encode in ASN.1 and sign.
- */
- tstamp = crypto_time();
- memset(vp, 0, sizeof(struct value));
- vp->tstamp = htonl(tstamp);
- vp->fstamp = hostval.tstamp;
- len = EVP_PKEY_size(pkey);
- vp->vallen = htonl(len);
- vp->ptr = emalloc(len);
- 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",
- ERR_error_string(ERR_get_error(), NULL));
- 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, len);
- if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
- vp->siglen = htonl(len);
- return (XEVNT_OK);
- }
- /*
- * crypto_ident - construct extension field for identity scheme
- *
- * This routine determines which identity scheme is in use and
- * constructs an extension field for that scheme.
- */
- u_int
- crypto_ident(
- struct peer *peer /* peer structure pointer */
- )
- {
- char filename[MAXFILENAME + 1];
- /*
- * 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.
- */
- 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);
- }
- if (peer->crypto & CRYPTO_FLAG_IFF) {
- snprintf(filename, MAXFILENAME, "ntpkey_iff_%s",
- peer->issuer);
- peer->ident_pkey = crypto_key(filename, &peer->fstamp);
- 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);
- }
- 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 (p…