2 * ntp_crypto.c - NTP version 4 public key routines
10 #include <stdlib.h> /* strtoul */
11 #include <sys/types.h>
12 #include <sys/param.h>
17 #include "ntp_stdlib.h"
18 #include "ntp_unixtime.h"
19 #include "ntp_string.h"
20 #include "ntp_random.h"
21 #include "ntp_assert.h"
22 #include "ntp_calendar.h"
23 #include "ntp_leapsec.h"
25 #include "openssl/asn1.h"
26 #include "openssl/bn.h"
27 #include "openssl/crypto.h"
28 #include "openssl/err.h"
29 #include "openssl/evp.h"
30 #include "openssl/opensslv.h"
31 #include "openssl/pem.h"
32 #include "openssl/rand.h"
33 #include "openssl/x509.h"
34 #include "openssl/x509v3.h"
35 #include "libssl_compat.h"
38 #include "ntp_syscall.h"
39 #endif /* KERNEL_PLL */
42 * calcomp - compare two calendar structures, ignoring yearday and weekday; like strcmp
43 * No, it's not a plotter. If you don't understand that, you're too young.
45 static int calcomp(struct calendar *pjd1, struct calendar *pjd2)
47 int32_t diff; /* large enough to hold the signed difference between two uint16_t values */
49 diff = pjd1->year - pjd2->year;
50 if (diff < 0) return -1; else if (diff > 0) return 1;
51 /* same year; compare months */
52 diff = pjd1->month - pjd2->month;
53 if (diff < 0) return -1; else if (diff > 0) return 1;
54 /* same year and month; compare monthday */
55 diff = pjd1->monthday - pjd2->monthday;
56 if (diff < 0) return -1; else if (diff > 0) return 1;
57 /* same year and month and monthday; compare time */
58 diff = pjd1->hour - pjd2->hour;
59 if (diff < 0) return -1; else if (diff > 0) return 1;
60 diff = pjd1->minute - pjd2->minute;
61 if (diff < 0) return -1; else if (diff > 0) return 1;
62 diff = pjd1->second - pjd2->second;
63 if (diff < 0) return -1; else if (diff > 0) return 1;
69 * Extension field message format
71 * These are always signed and saved before sending in network byte
72 * order. They must be converted to and from host byte order for
76 * | op | len | <- extension pointer
80 * | timestamp | <- value pointer
97 * The CRYPTO_RESP bit is set to 0 for requests, 1 for responses.
98 * Requests carry the association ID of the receiver; responses carry
99 * the association ID of the sender. Some messages include only the
100 * operation/length and association ID words and so have length 8
101 * octets. Ohers include the value structure and associated value and
102 * signature fields. These messages include the timestamp, filestamp,
103 * value and signature words and so have length at least 24 octets. The
104 * signature and/or value fields can be empty, in which case the
105 * respective length words are zero. An empty value with nonempty
106 * signature is syntactically valid, but semantically questionable.
108 * The filestamp represents the time when a cryptographic data file such
109 * as a public/private key pair is created. It follows every reference
110 * depending on that file and serves as a means to obsolete earlier data
111 * of the same type. The timestamp represents the time when the
112 * cryptographic data of the message were last signed. Creation of a
113 * cryptographic data file or signing a message can occur only when the
114 * creator or signor is synchronized to an authoritative source and
115 * proventicated to a trusted authority.
117 * Note there are several conditions required for server trust. First,
118 * the public key on the server certificate must be verified, which can
119 * involve a hike along the certificate trail to a trusted host. Next,
120 * the server trust must be confirmed by one of several identity
121 * schemes. Valid cryptographic values are signed with attached
122 * timestamp and filestamp. Individual packet trust is confirmed
123 * relative to these values by a message digest with keys generated by a
124 * reverse-order pseudorandom hash.
126 * State decomposition. These flags are lit in the order given. They are
127 * dim only when the association is demobilized.
129 * CRYPTO_FLAG_ENAB Lit upon acceptance of a CRYPTO_ASSOC message
130 * CRYPTO_FLAG_CERT Lit when a self-digned trusted certificate is
132 * CRYPTO_FLAG_VRFY Lit when identity is confirmed.
133 * CRYPTO_FLAG_PROV Lit when the first signature is verified.
134 * CRYPTO_FLAG_COOK Lit when a valid cookie is accepted.
135 * CRYPTO_FLAG_AUTO Lit when valid autokey values are accepted.
136 * CRYPTO_FLAG_SIGN Lit when the server signed certificate is
138 * CRYPTO_FLAG_LEAP Lit when the leapsecond values are accepted.
143 #define TAI_1972 10 /* initial TAI offset (s) */
144 #define MAX_LEAP 100 /* max UTC leapseconds (s) */
145 #define VALUE_LEN (6 * 4) /* min response field length */
146 #define MAX_VALLEN (65535 - VALUE_LEN)
147 #define YEAR (60 * 60 * 24 * 365) /* seconds in year */
150 * Global cryptodata in host byte order
152 u_int32 crypto_flags = 0x0; /* status word */
153 int crypto_nid = KEY_TYPE_MD5; /* digest nid */
154 char *sys_hostname = NULL;
155 char *sys_groupname = NULL;
156 static char *host_filename = NULL; /* host file name */
157 static char *ident_filename = NULL; /* group file name */
160 * Global cryptodata in network byte order
162 struct cert_info *cinfo = NULL; /* certificate info/value cache */
163 struct cert_info *cert_host = NULL; /* host certificate */
164 struct pkey_info *pkinfo = NULL; /* key info/value cache */
165 struct value hostval; /* host value */
166 struct value pubkey; /* public key */
167 struct value tai_leap; /* leapseconds values */
168 struct pkey_info *iffkey_info = NULL; /* IFF keys */
169 struct pkey_info *gqkey_info = NULL; /* GQ keys */
170 struct pkey_info *mvkey_info = NULL; /* MV keys */
173 * Private cryptodata in host byte order
175 static char *passwd = NULL; /* private key password */
176 static EVP_PKEY *host_pkey = NULL; /* host key */
177 static EVP_PKEY *sign_pkey = NULL; /* sign key */
178 static const EVP_MD *sign_digest = NULL; /* sign digest */
179 static u_int sign_siglen; /* sign key length */
180 static char *rand_file = NULL; /* random seed file */
185 static int crypto_verify (struct exten *, struct value *,
187 static int crypto_encrypt (const u_char *, u_int, keyid_t *,
189 static int crypto_alice (struct peer *, struct value *);
190 static int crypto_alice2 (struct peer *, struct value *);
191 static int crypto_alice3 (struct peer *, struct value *);
192 static int crypto_bob (struct exten *, struct value *);
193 static int crypto_bob2 (struct exten *, struct value *);
194 static int crypto_bob3 (struct exten *, struct value *);
195 static int crypto_iff (struct exten *, struct peer *);
196 static int crypto_gq (struct exten *, struct peer *);
197 static int crypto_mv (struct exten *, struct peer *);
198 static int crypto_send (struct exten *, struct value *, int);
199 static tstamp_t crypto_time (void);
200 static void asn_to_calendar (const ASN1_TIME *, struct calendar*);
201 static struct cert_info *cert_parse (const u_char *, long, tstamp_t);
202 static int cert_sign (struct exten *, struct value *);
203 static struct cert_info *cert_install (struct exten *, struct peer *);
204 static int cert_hike (struct peer *, struct cert_info *);
205 static void cert_free (struct cert_info *);
206 static struct pkey_info *crypto_key (char *, char *, sockaddr_u *);
207 static void bighash (BIGNUM *, BIGNUM *);
208 static struct cert_info *crypto_cert (char *);
209 static u_int exten_payload_size(const struct exten *);
213 readlink(char * link, char * file, int len) {
219 * session_key - generate session key
221 * This routine generates a session key from the source address,
222 * destination address, key ID and private value. The value of the
223 * session key is the MD5 hash of these values, while the next key ID is
224 * the first four octets of the hash.
226 * Returns the next key ID or 0 if there is no destination address.
230 sockaddr_u *srcadr, /* source address */
231 sockaddr_u *dstadr, /* destination address */
232 keyid_t keyno, /* key ID */
233 keyid_t private, /* private value */
234 u_long lifetime /* key lifetime */
237 EVP_MD_CTX *ctx; /* message digest context */
238 u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
239 keyid_t keyid; /* key identifer */
240 u_int32 header[10]; /* data in network byte order */
247 * Generate the session key and key ID. If the lifetime is
248 * greater than zero, install the key and call it trusted.
253 header[0] = NSRCADR(srcadr);
254 header[1] = NSRCADR(dstadr);
255 header[2] = htonl(keyno);
256 header[3] = htonl(private);
257 hdlen = 4 * sizeof(u_int32);
261 memcpy(&header[0], PSOCK_ADDR6(srcadr),
262 sizeof(struct in6_addr));
263 memcpy(&header[4], PSOCK_ADDR6(dstadr),
264 sizeof(struct in6_addr));
265 header[8] = htonl(keyno);
266 header[9] = htonl(private);
267 hdlen = 10 * sizeof(u_int32);
270 ctx = EVP_MD_CTX_new();
271 EVP_DigestInit(ctx, EVP_get_digestbynid(crypto_nid));
272 EVP_DigestUpdate(ctx, (u_char *)header, hdlen);
273 EVP_DigestFinal(ctx, dgst, &len);
274 EVP_MD_CTX_free(ctx);
275 memcpy(&keyid, dgst, 4);
276 keyid = ntohl(keyid);
278 MD5auth_setkey(keyno, crypto_nid, dgst, len, NULL);
279 authtrust(keyno, lifetime);
281 DPRINTF(2, ("session_key: %s > %s %08x %08x hash %08x life %lu\n",
282 stoa(srcadr), stoa(dstadr), keyno,
283 private, keyid, lifetime));
290 * make_keylist - generate key list
294 * XEVNT_ERR protocol error
296 * This routine constructs a pseudo-random sequence by repeatedly
297 * hashing the session key starting from a given source address,
298 * destination address, private value and the next key ID of the
299 * preceeding session key. The last entry on the list is saved along
300 * with its sequence number and public signature.
304 struct peer *peer, /* peer structure pointer */
305 struct interface *dstadr /* interface */
308 EVP_MD_CTX *ctx; /* signature context */
309 tstamp_t tstamp; /* NTP timestamp */
310 struct autokey *ap; /* autokey pointer */
311 struct value *vp; /* value pointer */
312 keyid_t keyid = 0; /* next key ID */
313 keyid_t cookie; /* private value */
322 * Allocate the key list if necessary.
324 tstamp = crypto_time();
325 if (peer->keylist == NULL)
326 peer->keylist = eallocarray(NTP_MAXSESSION,
330 * Generate an initial key ID which is unique and greater than
334 keyid = ntp_random() & 0xffffffff;
335 if (keyid <= NTP_MAXKEY)
338 if (authhavekey(keyid))
344 * Generate up to NTP_MAXSESSION session keys. Stop if the
345 * next one would not be unique or not a session key ID or if
346 * it would expire before the next poll. The private value
347 * included in the hash is zero if broadcast mode, the peer
348 * cookie if client mode or the host cookie if symmetric modes.
350 mpoll = 1 << min(peer->ppoll, peer->hpoll);
351 lifetime = min(1U << sys_automax, NTP_MAXSESSION * mpoll);
352 if (peer->hmode == MODE_BROADCAST)
355 cookie = peer->pcookie;
356 for (i = 0; i < NTP_MAXSESSION; i++) {
357 peer->keylist[i] = keyid;
359 keyid = session_key(&dstadr->sin, &peer->srcadr, keyid,
360 cookie, lifetime + mpoll);
362 if (auth_havekey(keyid) || keyid <= NTP_MAXKEY ||
363 lifetime < 0 || tstamp == 0)
368 * Save the last session key ID, sequence number and timestamp,
369 * then sign these values for later retrieval by the clients. Be
370 * careful not to use invalid key media. Use the public values
371 * timestamp as filestamp.
375 vp->ptr = emalloc(sizeof(struct autokey));
376 ap = (struct autokey *)vp->ptr;
377 ap->seq = htonl(peer->keynumber);
378 ap->key = htonl(keyid);
379 vp->tstamp = htonl(tstamp);
380 vp->fstamp = hostval.tstamp;
381 vp->vallen = htonl(sizeof(struct autokey));
385 vp->sig = emalloc(sign_siglen);
386 ctx = EVP_MD_CTX_new();
387 EVP_SignInit(ctx, sign_digest);
388 EVP_SignUpdate(ctx, (u_char *)vp, 12);
389 EVP_SignUpdate(ctx, vp->ptr, sizeof(struct autokey));
390 if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
391 INSIST(len <= sign_siglen);
392 vp->siglen = htonl(len);
393 peer->flags |= FLAG_ASSOC;
395 EVP_MD_CTX_free(ctx);
397 DPRINTF(1, ("make_keys: %d %08x %08x ts %u fs %u poll %d\n",
398 peer->keynumber, keyid, cookie, ntohl(vp->tstamp),
399 ntohl(vp->fstamp), peer->hpoll));
405 * crypto_recv - parse extension fields
407 * This routine is called when the packet has been matched to an
408 * association and passed sanity, format and MAC checks. We believe the
409 * extension field values only if the field has proper format and
410 * length, the timestamp and filestamp are valid and the signature has
411 * valid length and is verified. There are a few cases where some values
412 * are believed even if the signature fails, but only if the proventic
417 * XEVNT_ERR protocol error
418 * XEVNT_LEN bad field format or length
422 struct peer *peer, /* peer structure pointer */
423 struct recvbuf *rbufp /* packet buffer pointer */
426 const EVP_MD *dp; /* message digest algorithm */
427 u_int32 *pkt; /* receive packet pointer */
428 struct autokey *ap, *bp; /* autokey pointer */
429 struct exten *ep, *fp; /* extension pointers */
430 struct cert_info *xinfo; /* certificate info pointer */
431 int macbytes; /* length of MAC field, signed by intention */
432 int authlen; /* offset of MAC field */
433 associd_t associd; /* association ID */
434 tstamp_t fstamp = 0; /* filestamp */
435 u_int len; /* extension field length */
436 u_int code; /* extension field opcode */
437 u_int vallen = 0; /* value length */
438 X509 *cert; /* X509 certificate */
439 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
440 keyid_t cookie; /* crumbles */
441 int hismode; /* packet mode */
447 * Initialize. Note that the packet has already been checked for
448 * valid format and extension field lengths. First extract the
449 * field length, command code and association ID in host byte
450 * order. These are used with all commands and modes. Then check
451 * the version number, which must be 2, and length, which must
452 * be at least 8 for requests and VALUE_LEN (24) for responses.
453 * Packets that fail either test sink without a trace. The
454 * association ID is saved only if nonzero.
456 authlen = LEN_PKT_NOMAC;
457 hismode = (int)PKT_MODE((&rbufp->recv_pkt)->li_vn_mode);
458 while ((macbytes = rbufp->recv_length - authlen) > (int)MAX_MAC_LEN) {
459 /* We can be reasonably sure that we can read at least
460 * the opcode and the size field here. More stringent
461 * checks follow up shortly.
463 pkt = (u_int32 *)&rbufp->recv_pkt + authlen / 4;
464 ep = (struct exten *)pkt;
465 code = ntohl(ep->opcode) & 0xffff0000;
466 len = ntohl(ep->opcode) & 0x0000ffff;
467 // HMS: Why pkt[1] instead of ep->associd ?
468 associd = (associd_t)ntohl(pkt[1]);
470 DPRINTF(1, ("crypto_recv: flags 0x%x ext offset %d len %u code 0x%x associd %d\n",
471 peer->crypto, authlen, len, code >> 16,
475 * Check version number and field length. If bad,
476 * quietly ignore the packet.
478 if (((code >> 24) & 0x3f) != CRYPTO_VN || len < 8) {
480 code |= CRYPTO_ERROR;
483 /* Check if the declared size fits into the remaining
484 * buffer. We *know* 'macbytes' > 0 here!
486 if (len > (u_int)macbytes) {
487 DPRINTF(1, ("crypto_recv: possible attack detected, associd %d\n",
492 /* Check if the paylod of the extension fits into the
495 if (len >= VALUE_LEN) {
496 fstamp = ntohl(ep->fstamp);
497 vallen = ntohl(ep->vallen);
499 * Bug 2761: I hope this isn't too early...
502 || len - VALUE_LEN < vallen)
508 * Install status word, host name, signature scheme and
509 * association ID. In OpenSSL the signature algorithm is
510 * bound to the digest algorithm, so the NID completely
511 * defines the signature scheme. Note the request and
512 * response are identical, but neither is validated by
513 * signature. The request is processed here only in
514 * symmetric modes. The server name field might be
515 * useful to implement access controls in future.
520 * If our state machine is running when this
521 * message arrives, the other fellow might have
522 * restarted. However, this could be an
523 * intruder, so just clamp the poll interval and
524 * find out for ourselves. Otherwise, pass the
525 * extension field to the transmit side.
527 if (peer->crypto & CRYPTO_FLAG_CERT) {
532 if (peer->assoc != associd) {
536 free(peer->cmmd); /* will be set again! */
540 fp->associd = htonl(peer->associd);
544 case CRYPTO_ASSOC | CRYPTO_RESP:
547 * Discard the message if it has already been
548 * stored or the message has been amputated.
551 if (peer->assoc != associd)
555 INSIST(len >= VALUE_LEN);
556 if (vallen == 0 || vallen > MAXHOSTNAME ||
557 len - VALUE_LEN < vallen) {
561 DPRINTF(1, ("crypto_recv: ident host 0x%x %d server 0x%x %d\n",
562 crypto_flags, peer->associd, fstamp,
564 temp32 = crypto_flags & CRYPTO_FLAG_MASK;
567 * If the client scheme is PC, the server scheme
568 * must be PC. The public key and identity are
569 * presumed valid, so we skip the certificate
570 * and identity exchanges and move immediately
571 * to the cookie exchange which confirms the
574 if (crypto_flags & CRYPTO_FLAG_PRIV) {
575 if (!(fstamp & CRYPTO_FLAG_PRIV)) {
579 fstamp |= CRYPTO_FLAG_CERT |
580 CRYPTO_FLAG_VRFY | CRYPTO_FLAG_SIGN;
583 * It is an error if either peer supports
584 * identity, but the other does not.
586 } else if (hismode == MODE_ACTIVE || hismode ==
588 if ((temp32 && !(fstamp &
589 CRYPTO_FLAG_MASK)) ||
590 (!temp32 && (fstamp &
591 CRYPTO_FLAG_MASK))) {
598 * Discard the message if the signature digest
599 * NID is not supported.
601 temp32 = (fstamp >> 16) & 0xffff;
603 (const EVP_MD *)EVP_get_digestbynid(temp32);
610 * Save status word, host name and message
611 * digest/signature type. If this is from a
612 * broadcast and the association ID has changed,
613 * request the autokey values.
615 peer->assoc = associd;
616 if (hismode == MODE_SERVER)
617 fstamp |= CRYPTO_FLAG_AUTO;
618 if (!(fstamp & CRYPTO_FLAG_TAI))
619 fstamp |= CRYPTO_FLAG_LEAP;
620 RAND_bytes((u_char *)&peer->hcookie, 4);
621 peer->crypto = fstamp;
623 if (peer->subject != NULL)
625 peer->subject = emalloc(vallen + 1);
626 memcpy(peer->subject, ep->pkt, vallen);
627 peer->subject[vallen] = '\0';
628 if (peer->issuer != NULL)
630 peer->issuer = estrdup(peer->subject);
631 snprintf(statstr, sizeof(statstr),
632 "assoc %d %d host %s %s", peer->associd,
633 peer->assoc, peer->subject,
635 record_crypto_stats(&peer->srcadr, statstr);
636 DPRINTF(1, ("crypto_recv: %s\n", statstr));
640 * Decode X509 certificate in ASN.1 format and extract
641 * the data containing, among other things, subject
642 * name and public key. In the default identification
643 * scheme, the certificate trail is followed to a self
644 * signed trusted certificate.
646 case CRYPTO_CERT | CRYPTO_RESP:
649 * Discard the message if empty or invalid.
654 if ((rval = crypto_verify(ep, NULL, peer)) !=
659 * Scan the certificate list to delete old
660 * versions and link the newest version first on
661 * the list. Then, verify the signature. If the
662 * certificate is bad or missing, just ignore
665 if ((xinfo = cert_install(ep, peer)) == NULL) {
669 if ((rval = cert_hike(peer, xinfo)) != XEVNT_OK)
673 * We plug in the public key and lifetime from
674 * the first certificate received. However, note
675 * that this certificate might not be signed by
676 * the server, so we can't check the
677 * signature/digest NID.
679 if (peer->pkey == NULL) {
680 puch = xinfo->cert.ptr;
681 cert = d2i_X509(NULL, &puch,
682 ntohl(xinfo->cert.vallen));
683 peer->pkey = X509_get_pubkey(cert);
686 peer->flash &= ~TEST8;
688 snprintf(statstr, sizeof(statstr),
689 "cert %s %s 0x%x %s (%u) fs %u",
690 xinfo->subject, xinfo->issuer, xinfo->flags,
691 OBJ_nid2ln(temp32), temp32,
693 record_crypto_stats(&peer->srcadr, statstr);
694 DPRINTF(1, ("crypto_recv: %s\n", statstr));
698 * Schnorr (IFF) identity scheme. This scheme is
699 * designed for use with shared secret server group keys
700 * and where the certificate may be generated by a third
701 * party. The client sends a challenge to the server,
702 * which performs a calculation and returns the result.
703 * A positive result is possible only if both client and
704 * server contain the same secret group key.
706 case CRYPTO_IFF | CRYPTO_RESP:
709 * Discard the message if invalid.
711 if ((rval = crypto_verify(ep, NULL, peer)) !=
716 * If the challenge matches the response, the
717 * server public key, signature and identity are
718 * all verified at the same time. The server is
719 * declared trusted, so we skip further
720 * certificate exchanges and move immediately to
721 * the cookie exchange.
723 if ((rval = crypto_iff(ep, peer)) != XEVNT_OK)
726 peer->crypto |= CRYPTO_FLAG_VRFY;
727 peer->flash &= ~TEST8;
728 snprintf(statstr, sizeof(statstr), "iff %s fs %u",
729 peer->issuer, ntohl(ep->fstamp));
730 record_crypto_stats(&peer->srcadr, statstr);
731 DPRINTF(1, ("crypto_recv: %s\n", statstr));
735 * Guillou-Quisquater (GQ) identity scheme. This scheme
736 * is designed for use with public certificates carrying
737 * the GQ public key in an extension field. The client
738 * sends a challenge to the server, which performs a
739 * calculation and returns the result. A positive result
740 * is possible only if both client and server contain
741 * the same group key and the server has the matching GQ
744 case CRYPTO_GQ | CRYPTO_RESP:
747 * Discard the message if invalid
749 if ((rval = crypto_verify(ep, NULL, peer)) !=
754 * If the challenge matches the response, the
755 * server public key, signature and identity are
756 * all verified at the same time. The server is
757 * declared trusted, so we skip further
758 * certificate exchanges and move immediately to
759 * the cookie exchange.
761 if ((rval = crypto_gq(ep, peer)) != XEVNT_OK)
764 peer->crypto |= CRYPTO_FLAG_VRFY;
765 peer->flash &= ~TEST8;
766 snprintf(statstr, sizeof(statstr), "gq %s fs %u",
767 peer->issuer, ntohl(ep->fstamp));
768 record_crypto_stats(&peer->srcadr, statstr);
769 DPRINTF(1, ("crypto_recv: %s\n", statstr));
773 * Mu-Varadharajan (MV) identity scheme. This scheme is
774 * designed for use with three levels of trust, trusted
775 * host, server and client. The trusted host key is
776 * opaque to servers and clients; the server keys are
777 * opaque to clients and each client key is different.
778 * Client keys can be revoked without requiring new key
781 case CRYPTO_MV | CRYPTO_RESP:
784 * Discard the message if invalid.
786 if ((rval = crypto_verify(ep, NULL, peer)) !=
791 * If the challenge matches the response, the
792 * server public key, signature and identity are
793 * all verified at the same time. The server is
794 * declared trusted, so we skip further
795 * certificate exchanges and move immediately to
796 * the cookie exchange.
798 if ((rval = crypto_mv(ep, peer)) != XEVNT_OK)
801 peer->crypto |= CRYPTO_FLAG_VRFY;
802 peer->flash &= ~TEST8;
803 snprintf(statstr, sizeof(statstr), "mv %s fs %u",
804 peer->issuer, ntohl(ep->fstamp));
805 record_crypto_stats(&peer->srcadr, statstr);
806 DPRINTF(1, ("crypto_recv: %s\n", statstr));
811 * Cookie response in client and symmetric modes. If the
812 * cookie bit is set, the working cookie is the EXOR of
813 * the current and new values.
815 case CRYPTO_COOK | CRYPTO_RESP:
818 * Discard the message if invalid or signature
819 * not verified with respect to the cookie
822 if ((rval = crypto_verify(ep, &peer->cookval,
827 * Decrypt the cookie, hunting all the time for
830 if (vallen == (u_int)EVP_PKEY_size(host_pkey)) {
831 RSA *rsa = EVP_PKEY_get0_RSA(host_pkey);
832 u_int32 *cookiebuf = malloc(RSA_size(rsa));
838 if (RSA_private_decrypt(vallen,
842 RSA_PKCS1_OAEP_PADDING) != 4) {
847 cookie = ntohl(*cookiebuf);
856 * Install cookie values and light the cookie
857 * bit. If this is not broadcast client mode, we
861 if (hismode == MODE_ACTIVE || hismode ==
863 peer->pcookie = peer->hcookie ^ cookie;
865 peer->pcookie = cookie;
866 peer->crypto |= CRYPTO_FLAG_COOK;
867 peer->flash &= ~TEST8;
868 snprintf(statstr, sizeof(statstr),
869 "cook %x ts %u fs %u", peer->pcookie,
870 ntohl(ep->tstamp), ntohl(ep->fstamp));
871 record_crypto_stats(&peer->srcadr, statstr);
872 DPRINTF(1, ("crypto_recv: %s\n", statstr));
876 * Install autokey values in broadcast client and
877 * symmetric modes. We have to do this every time the
878 * sever/peer cookie changes or a new keylist is
879 * rolled. Ordinarily, this is automatic as this message
880 * is piggybacked on the first NTP packet sent upon
881 * either of these events. Note that a broadcast client
882 * or symmetric peer can receive this response without a
885 case CRYPTO_AUTO | CRYPTO_RESP:
888 * Discard the message if invalid or signature
889 * not verified with respect to the receive
892 if ((rval = crypto_verify(ep, &peer->recval,
897 * Discard the message if a broadcast client and
898 * the association ID does not match. This might
899 * happen if a broacast server restarts the
900 * protocol. A protocol restart will occur at
901 * the next ASSOC message.
903 if ((peer->cast_flags & MDF_BCLNT) &&
904 peer->assoc != associd)
908 * Install autokey values and light the
909 * autokey bit. This is not hard.
914 if (peer->recval.ptr == NULL)
916 emalloc(sizeof(struct autokey));
917 bp = (struct autokey *)peer->recval.ptr;
918 peer->recval.tstamp = ep->tstamp;
919 peer->recval.fstamp = ep->fstamp;
920 ap = (struct autokey *)ep->pkt;
921 bp->seq = ntohl(ap->seq);
922 bp->key = ntohl(ap->key);
923 peer->pkeyid = bp->key;
924 peer->crypto |= CRYPTO_FLAG_AUTO;
925 peer->flash &= ~TEST8;
926 snprintf(statstr, sizeof(statstr),
927 "auto seq %d key %x ts %u fs %u", bp->seq,
928 bp->key, ntohl(ep->tstamp),
930 record_crypto_stats(&peer->srcadr, statstr);
931 DPRINTF(1, ("crypto_recv: %s\n", statstr));
935 * X509 certificate sign response. Validate the
936 * certificate signed by the server and install. Later
937 * this can be provided to clients of this server in
938 * lieu of the self signed certificate in order to
939 * validate the public key.
941 case CRYPTO_SIGN | CRYPTO_RESP:
944 * Discard the message if invalid.
946 if ((rval = crypto_verify(ep, NULL, peer)) !=
951 * Scan the certificate list to delete old
952 * versions and link the newest version first on
955 if ((xinfo = cert_install(ep, peer)) == NULL) {
959 peer->crypto |= CRYPTO_FLAG_SIGN;
960 peer->flash &= ~TEST8;
962 snprintf(statstr, sizeof(statstr),
963 "sign %s %s 0x%x %s (%u) fs %u",
964 xinfo->subject, xinfo->issuer, xinfo->flags,
965 OBJ_nid2ln(temp32), temp32,
967 record_crypto_stats(&peer->srcadr, statstr);
968 DPRINTF(1, ("crypto_recv: %s\n", statstr));
972 * Install leapseconds values. While the leapsecond
973 * values epoch, TAI offset and values expiration epoch
974 * are retained, only the current TAI offset is provided
975 * via the kernel to other applications.
977 case CRYPTO_LEAP | CRYPTO_RESP:
979 * Discard the message if invalid. We can't
980 * compare the value timestamps here, as they
981 * can be updated by different servers.
983 rval = crypto_verify(ep, NULL, peer);
984 if ((rval != XEVNT_OK ) ||
985 (vallen != 3*sizeof(uint32_t)) )
988 /* Check if we can update the basic TAI offset
989 * for our current leap frame. This is a hack
990 * and ignores the time stamps in the autokey
993 if (sys_leap != LEAP_NOTINSYNC)
994 leapsec_autokey_tai(ntohl(ep->pkt[0]),
995 rbufp->recv_time.l_ui, NULL);
996 tai_leap.tstamp = ep->tstamp;
997 tai_leap.fstamp = ep->fstamp;
999 mprintf_event(EVNT_TAI, peer,
1000 "%d seconds", ntohl(ep->pkt[0]));
1001 peer->crypto |= CRYPTO_FLAG_LEAP;
1002 peer->flash &= ~TEST8;
1003 snprintf(statstr, sizeof(statstr),
1004 "leap TAI offset %d at %u expire %u fs %u",
1005 ntohl(ep->pkt[0]), ntohl(ep->pkt[1]),
1006 ntohl(ep->pkt[2]), ntohl(ep->fstamp));
1007 record_crypto_stats(&peer->srcadr, statstr);
1008 DPRINTF(1, ("crypto_recv: %s\n", statstr));
1012 * We come here in symmetric modes for miscellaneous
1013 * commands that have value fields but are processed on
1014 * the transmit side. All we need do here is check for
1015 * valid field length. Note that ASSOC is handled
1024 if (len < VALUE_LEN) {
1031 * We come here in symmetric modes for requests
1032 * requiring a response (above plus AUTO and LEAP) and
1033 * for responses. If a request, save the extension field
1034 * for later; invalid requests will be caught on the
1035 * transmit side. If an error or invalid response,
1036 * declare a protocol error.
1039 if (code & (CRYPTO_RESP | CRYPTO_ERROR)) {
1041 } else if (peer->cmmd == NULL) {
1043 memcpy(fp, ep, len);
1049 * The first error found terminates the extension field
1050 * scan and we return the laundry to the caller.
1052 if (rval != XEVNT_OK) {
1053 snprintf(statstr, sizeof(statstr),
1054 "%04x %d %02x %s", htonl(ep->opcode),
1055 associd, rval, eventstr(rval));
1056 record_crypto_stats(&peer->srcadr, statstr);
1057 DPRINTF(1, ("crypto_recv: %s\n", statstr));
1060 authlen += (len + 3) / 4 * 4;
1067 * crypto_xmit - construct extension fields
1069 * This routine is called both when an association is configured and
1070 * when one is not. The only case where this matters is to retrieve the
1071 * autokey information, in which case the caller has to provide the
1072 * association ID to match the association.
1074 * Side effect: update the packet offset.
1078 * XEVNT_CRT bad or missing certificate
1079 * XEVNT_ERR protocol error
1080 * XEVNT_LEN bad field format or length
1081 * XEVNT_PER host certificate expired
1085 struct peer *peer, /* peer structure pointer */
1086 struct pkt *xpkt, /* transmit packet pointer */
1087 struct recvbuf *rbufp, /* receive buffer pointer */
1088 int start, /* offset to extension field */
1089 struct exten *ep, /* extension pointer */
1090 keyid_t cookie /* session cookie */
1093 struct exten *fp; /* extension pointers */
1094 struct cert_info *cp, *xp, *yp; /* cert info/value pointer */
1095 sockaddr_u *srcadr_sin; /* source address */
1096 u_int32 *pkt; /* packet pointer */
1097 u_int opcode; /* extension field opcode */
1098 char certname[MAXHOSTNAME + 1]; /* subject name buffer */
1099 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1101 struct calendar tscal;
1110 * Generate the requested extension field request code, length
1111 * and association ID. If this is a response and the host is not
1112 * synchronized, light the error bit and go home.
1114 pkt = (u_int32 *)xpkt + start / 4;
1115 fp = (struct exten *)pkt;
1116 opcode = ntohl(ep->opcode);
1118 srcadr_sin = &peer->srcadr;
1119 if (!(opcode & CRYPTO_RESP))
1120 peer->opcode = ep->opcode;
1122 srcadr_sin = &rbufp->recv_srcadr;
1124 associd = (associd_t) ntohl(ep->associd);
1126 fp->opcode = htonl((opcode & 0xffff0000) | len);
1127 fp->associd = ep->associd;
1129 tstamp = crypto_time();
1130 switch (opcode & 0xffff0000) {
1133 * Send association request and response with status word and
1134 * host name. Note, this message is not signed and the filestamp
1135 * contains only the status word.
1138 case CRYPTO_ASSOC | CRYPTO_RESP:
1139 len = crypto_send(fp, &hostval, start);
1140 fp->fstamp = htonl(crypto_flags);
1144 * Send certificate request. Use the values from the extension
1148 memset(&vtemp, 0, sizeof(vtemp));
1149 vtemp.tstamp = ep->tstamp;
1150 vtemp.fstamp = ep->fstamp;
1151 vtemp.vallen = ep->vallen;
1152 vtemp.ptr = (u_char *)ep->pkt;
1153 len = crypto_send(fp, &vtemp, start);
1157 * Send sign request. Use the host certificate, which is self-
1158 * signed and may or may not be trusted.
1161 (void)ntpcal_ntp_to_date(&tscal, tstamp, NULL);
1162 if ((calcomp(&tscal, &(cert_host->first)) < 0)
1163 || (calcomp(&tscal, &(cert_host->last)) > 0))
1166 len = crypto_send(fp, &cert_host->cert, start);
1170 * Send certificate response. Use the name in the extension
1171 * field to find the certificate in the cache. If the request
1172 * contains no subject name, assume the name of this host. This
1173 * is for backwards compatibility. Private certificates are
1176 * There may be several certificates matching the request. First
1177 * choice is a self-signed trusted certificate; second choice is
1178 * any certificate signed by another host. There is no third
1181 case CRYPTO_CERT | CRYPTO_RESP:
1182 vallen = exten_payload_size(ep); /* Must be <64k */
1183 if (vallen == 0 || vallen >= sizeof(certname) ) {
1189 * Find all public valid certificates with matching
1190 * subject. If a self-signed, trusted certificate is
1191 * found, use that certificate. If not, use the last non
1192 * self-signed certificate.
1194 memcpy(certname, ep->pkt, vallen);
1195 certname[vallen] = '\0';
1197 for (cp = cinfo; cp != NULL; cp = cp->link) {
1198 if (cp->flags & (CERT_PRIV | CERT_ERROR))
1201 if (strcmp(certname, cp->subject) != 0)
1204 if (strcmp(certname, cp->issuer) != 0)
1206 else if (cp ->flags & CERT_TRUST)
1212 * Be careful who you trust. If the certificate is not
1213 * found, return an empty response. Note that we dont
1214 * enforce lifetimes here.
1216 * The timestamp and filestamp are taken from the
1217 * certificate value structure. For all certificates the
1218 * timestamp is the latest signature update time. For
1219 * host and imported certificates the filestamp is the
1220 * creation epoch. For signed certificates the filestamp
1221 * is the creation epoch of the trusted certificate at
1222 * the root of the certificate trail. In principle, this
1223 * allows strong checking for signature masquerade.
1233 len = crypto_send(fp, &xp->cert, start);
1237 * Send challenge in Schnorr (IFF) identity scheme.
1241 break; /* hack attack */
1243 if ((rval = crypto_alice(peer, &vtemp)) == XEVNT_OK) {
1244 len = crypto_send(fp, &vtemp, start);
1250 * Send response in Schnorr (IFF) identity scheme.
1252 case CRYPTO_IFF | CRYPTO_RESP:
1253 if ((rval = crypto_bob(ep, &vtemp)) == XEVNT_OK) {
1254 len = crypto_send(fp, &vtemp, start);
1260 * Send challenge in Guillou-Quisquater (GQ) identity scheme.
1264 break; /* hack attack */
1266 if ((rval = crypto_alice2(peer, &vtemp)) == XEVNT_OK) {
1267 len = crypto_send(fp, &vtemp, start);
1273 * Send response in Guillou-Quisquater (GQ) identity scheme.
1275 case CRYPTO_GQ | CRYPTO_RESP:
1276 if ((rval = crypto_bob2(ep, &vtemp)) == XEVNT_OK) {
1277 len = crypto_send(fp, &vtemp, start);
1283 * Send challenge in MV identity scheme.
1287 break; /* hack attack */
1289 if ((rval = crypto_alice3(peer, &vtemp)) == XEVNT_OK) {
1290 len = crypto_send(fp, &vtemp, start);
1296 * Send response in MV identity scheme.
1298 case CRYPTO_MV | CRYPTO_RESP:
1299 if ((rval = crypto_bob3(ep, &vtemp)) == XEVNT_OK) {
1300 len = crypto_send(fp, &vtemp, start);
1306 * Send certificate sign response. The integrity of the request
1307 * certificate has already been verified on the receive side.
1308 * Sign the response using the local server key. Use the
1309 * filestamp from the request and use the timestamp as the
1310 * current time. Light the error bit if the certificate is
1311 * invalid or contains an unverified signature.
1313 case CRYPTO_SIGN | CRYPTO_RESP:
1314 if ((rval = cert_sign(ep, &vtemp)) == XEVNT_OK) {
1315 len = crypto_send(fp, &vtemp, start);
1321 * Send public key and signature. Use the values from the public
1325 len = crypto_send(fp, &pubkey, start);
1329 * Encrypt and send cookie and signature. Light the error bit if
1330 * anything goes wrong.
1332 case CRYPTO_COOK | CRYPTO_RESP:
1333 vallen = ntohl(ep->vallen); /* Must be <64k */
1335 || (vallen >= MAX_VALLEN)
1336 || (opcode & 0x0000ffff) < VALUE_LEN + vallen) {
1343 tcookie = peer->hcookie;
1344 if ((rval = crypto_encrypt((const u_char *)ep->pkt, vallen, &tcookie, &vtemp))
1346 len = crypto_send(fp, &vtemp, start);
1352 * Find peer and send autokey data and signature in broadcast
1353 * server and symmetric modes. Use the values in the autokey
1354 * structure. If no association is found, either the server has
1355 * restarted with new associations or some perp has replayed an
1356 * old message, in which case light the error bit.
1358 case CRYPTO_AUTO | CRYPTO_RESP:
1360 if ((peer = findpeerbyassoc(associd)) == NULL) {
1365 peer->flags &= ~FLAG_ASSOC;
1366 len = crypto_send(fp, &peer->sndval, start);
1370 * Send leapseconds values and signature. Use the values from
1371 * the tai structure. If no table has been loaded, just send an
1374 case CRYPTO_LEAP | CRYPTO_RESP:
1375 len = crypto_send(fp, &tai_leap, start);
1379 * Default - Send a valid command for unknown requests; send
1380 * an error response for unknown resonses.
1383 if (opcode & CRYPTO_RESP)
1388 * In case of error, flame the log. If a request, toss the
1389 * puppy; if a response, return so the sender can flame, too.
1391 if (rval != XEVNT_OK) {
1394 uint32 = CRYPTO_ERROR;
1396 fp->opcode |= htonl(uint32);
1397 snprintf(statstr, sizeof(statstr),
1398 "%04x %d %02x %s", opcode, associd, rval,
1400 record_crypto_stats(srcadr_sin, statstr);
1401 DPRINTF(1, ("crypto_xmit: %s\n", statstr));
1402 if (!(opcode & CRYPTO_RESP))
1405 DPRINTF(1, ("crypto_xmit: flags 0x%x offset %d len %d code 0x%x associd %d\n",
1406 crypto_flags, start, len, opcode >> 16, associd));
1412 * crypto_verify - verify the extension field value and signature
1416 * XEVNT_ERR protocol error
1417 * XEVNT_FSP bad filestamp
1418 * XEVNT_LEN bad field format or length
1419 * XEVNT_PUB bad or missing public key
1420 * XEVNT_SGL bad signature length
1421 * XEVNT_SIG signature not verified
1422 * XEVNT_TSP bad timestamp
1426 struct exten *ep, /* extension pointer */
1427 struct value *vp, /* value pointer */
1428 struct peer *peer /* peer structure pointer */
1431 EVP_PKEY *pkey; /* server public key */
1432 EVP_MD_CTX *ctx; /* signature context */
1433 tstamp_t tstamp, tstamp1 = 0; /* timestamp */
1434 tstamp_t fstamp, fstamp1 = 0; /* filestamp */
1435 u_int vallen; /* value length */
1436 u_int siglen; /* signature length */
1441 * We are extremely parannoyed. We require valid opcode, length,
1442 * association ID, timestamp, filestamp, public key, digest,
1443 * signature length and signature, where relevant. Note that
1444 * preliminary length checks are done in the main loop.
1446 len = ntohl(ep->opcode) & 0x0000ffff;
1447 opcode = ntohl(ep->opcode) & 0xffff0000;
1450 * Check for valid value header, association ID and extension
1451 * field length. Remember, it is not an error to receive an
1452 * unsolicited response; however, the response ID must match
1453 * the association ID.
1455 if (opcode & CRYPTO_ERROR)
1458 if (len < VALUE_LEN)
1461 if (opcode == (CRYPTO_AUTO | CRYPTO_RESP) && (peer->pmode ==
1462 MODE_BROADCAST || (peer->cast_flags & MDF_BCLNT))) {
1463 if (ntohl(ep->associd) != peer->assoc)
1466 if (ntohl(ep->associd) != peer->associd)
1471 * We have a valid value header. Check for valid value and
1472 * signature field lengths. The extension field length must be
1473 * long enough to contain the value header, value and signature.
1474 * Note both the value and signature field lengths are rounded
1475 * up to the next word (4 octets).
1477 vallen = ntohl(ep->vallen);
1479 || vallen > MAX_VALLEN)
1482 i = (vallen + 3) / 4;
1483 siglen = ntohl(ep->pkt[i++]);
1484 if ( siglen > MAX_VALLEN
1485 || len - VALUE_LEN < ((vallen + 3) / 4) * 4
1486 || len - VALUE_LEN - ((vallen + 3) / 4) * 4
1487 < ((siglen + 3) / 4) * 4)
1491 * Check for valid timestamp and filestamp. If the timestamp is
1492 * zero, the sender is not synchronized and signatures are
1493 * not possible. If nonzero the timestamp must not precede the
1494 * filestamp. The timestamp and filestamp must not precede the
1495 * corresponding values in the value structure, if present.
1497 tstamp = ntohl(ep->tstamp);
1498 fstamp = ntohl(ep->fstamp);
1502 if (tstamp < fstamp)
1506 tstamp1 = ntohl(vp->tstamp);
1507 fstamp1 = ntohl(vp->fstamp);
1508 if (tstamp1 != 0 && fstamp1 != 0) {
1509 if (tstamp < tstamp1)
1512 if ((tstamp < fstamp1 || fstamp < fstamp1))
1518 * At the time the certificate message is validated, the public
1519 * key in the message is not available. Thus, don't try to
1520 * verify the signature.
1522 if (opcode == (CRYPTO_CERT | CRYPTO_RESP))
1526 * Check for valid signature length, public key and digest
1529 if (crypto_flags & peer->crypto & CRYPTO_FLAG_PRIV)
1533 if (siglen == 0 || pkey == NULL || peer->digest == NULL)
1536 if (siglen != (u_int)EVP_PKEY_size(pkey))
1540 * Darn, I thought we would never get here. Verify the
1541 * signature. If the identity exchange is verified, light the
1542 * proventic bit. What a relief.
1544 ctx = EVP_MD_CTX_new();
1545 EVP_VerifyInit(ctx, peer->digest);
1546 /* XXX: the "+ 12" needs to be at least documented... */
1547 EVP_VerifyUpdate(ctx, (u_char *)&ep->tstamp, vallen + 12);
1548 if (EVP_VerifyFinal(ctx, (u_char *)&ep->pkt[i], siglen,
1550 EVP_MD_CTX_free(ctx);
1553 EVP_MD_CTX_free(ctx);
1555 if (peer->crypto & CRYPTO_FLAG_VRFY)
1556 peer->crypto |= CRYPTO_FLAG_PROV;
1562 * crypto_encrypt - construct vp (encrypted cookie and signature) from
1563 * the public key and cookie.
1567 * XEVNT_CKY bad or missing cookie
1568 * XEVNT_PUB bad or missing public key
1572 const u_char *ptr, /* Public Key */
1573 u_int vallen, /* Length of Public Key */
1574 keyid_t *cookie, /* server cookie */
1575 struct value *vp /* value pointer */
1578 EVP_PKEY *pkey; /* public key */
1579 EVP_MD_CTX *ctx; /* signature context */
1580 tstamp_t tstamp; /* NTP timestamp */
1585 * Extract the public key from the request.
1587 pkey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &ptr, vallen);
1589 msyslog(LOG_ERR, "crypto_encrypt: %s",
1590 ERR_error_string(ERR_get_error(), NULL));
1595 * Encrypt the cookie, encode in ASN.1 and sign.
1597 memset(vp, 0, sizeof(struct value));
1598 tstamp = crypto_time();
1599 vp->tstamp = htonl(tstamp);
1600 vp->fstamp = hostval.tstamp;
1601 vallen = EVP_PKEY_size(pkey);
1602 vp->vallen = htonl(vallen);
1603 vp->ptr = emalloc(vallen);
1605 temp32 = htonl(*cookie);
1606 if (RSA_public_encrypt(4, (u_char *)&temp32, puch,
1607 EVP_PKEY_get0_RSA(pkey), RSA_PKCS1_OAEP_PADDING) <= 0) {
1608 msyslog(LOG_ERR, "crypto_encrypt: %s",
1609 ERR_error_string(ERR_get_error(), NULL));
1611 EVP_PKEY_free(pkey);
1614 EVP_PKEY_free(pkey);
1618 vp->sig = emalloc(sign_siglen);
1619 ctx = EVP_MD_CTX_new();
1620 EVP_SignInit(ctx, sign_digest);
1621 EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
1622 EVP_SignUpdate(ctx, vp->ptr, vallen);
1623 if (EVP_SignFinal(ctx, vp->sig, &vallen, sign_pkey)) {
1624 INSIST(vallen <= sign_siglen);
1625 vp->siglen = htonl(vallen);
1627 EVP_MD_CTX_free(ctx);
1633 * crypto_ident - construct extension field for identity scheme
1635 * This routine determines which identity scheme is in use and
1636 * constructs an extension field for that scheme.
1639 * CRYTPO_IFF IFF scheme
1640 * CRYPTO_GQ GQ scheme
1641 * CRYPTO_MV MV scheme
1642 * CRYPTO_NULL no available scheme
1646 struct peer *peer /* peer structure pointer */
1649 char filename[MAXFILENAME];
1650 const char * scheme_name;
1654 * We come here after the group trusted host has been found; its
1655 * name defines the group name. Search the key cache for all
1656 * keys matching the same group name in order IFF, GQ and MV.
1657 * Use the first one available.
1660 if (peer->crypto & CRYPTO_FLAG_IFF) {
1661 scheme_name = "iff";
1662 scheme_id = CRYPTO_IFF;
1663 } else if (peer->crypto & CRYPTO_FLAG_GQ) {
1665 scheme_id = CRYPTO_GQ;
1666 } else if (peer->crypto & CRYPTO_FLAG_MV) {
1668 scheme_id = CRYPTO_MV;
1671 if (scheme_name != NULL) {
1672 snprintf(filename, sizeof(filename), "ntpkey_%spar_%s",
1673 scheme_name, peer->ident);
1674 peer->ident_pkey = crypto_key(filename, NULL,
1676 if (peer->ident_pkey != NULL)
1681 "crypto_ident: no identity parameters found for group %s",
1689 * crypto_args - construct extension field from arguments
1691 * This routine creates an extension field with current timestamps and
1692 * specified opcode, association ID and optional string. Note that the
1693 * extension field is created here, but freed after the crypto_xmit()
1694 * call in the protocol module.
1696 * Returns extension field pointer (no errors)
1698 * XXX: opcode and len should really be 32-bit quantities and
1699 * we should make sure that str is not too big.
1703 struct peer *peer, /* peer structure pointer */
1704 u_int opcode, /* operation code */
1705 associd_t associd, /* association ID */
1706 char *str /* argument string */
1709 tstamp_t tstamp; /* NTP timestamp */
1710 struct exten *ep; /* extension field pointer */
1711 u_int len; /* extension field length */
1714 tstamp = crypto_time();
1715 len = sizeof(struct exten);
1718 INSIST(slen < MAX_VALLEN);
1721 ep = emalloc_zero(len);
1725 REQUIRE(0 == (len & ~0x0000ffff));
1726 REQUIRE(0 == (opcode & ~0xffff0000));
1728 ep->opcode = htonl(opcode + len);
1729 ep->associd = htonl(associd);
1730 ep->tstamp = htonl(tstamp);
1731 ep->fstamp = hostval.tstamp;
1734 ep->vallen = htonl(slen);
1735 memcpy((char *)ep->pkt, str, slen);
1742 * crypto_send - construct extension field from value components
1744 * The value and signature fields are zero-padded to a word boundary.
1745 * Note: it is not polite to send a nonempty signature with zero
1746 * timestamp or a nonzero timestamp with an empty signature, but those
1747 * rules are not enforced here.
1749 * XXX This code won't work on a box with 16-bit ints.
1753 struct exten *ep, /* extension field pointer */
1754 struct value *vp, /* value pointer */
1755 int start /* buffer offset */
1758 u_int len, vallen, siglen, opcode;
1762 * Calculate extension field length and check for buffer
1763 * overflow. Leave room for the MAC.
1765 len = 16; /* XXX Document! */
1766 vallen = ntohl(vp->vallen);
1767 INSIST(vallen <= MAX_VALLEN);
1768 len += ((vallen + 3) / 4 + 1) * 4;
1769 siglen = ntohl(vp->siglen);
1770 len += ((siglen + 3) / 4 + 1) * 4;
1771 if (start + len > sizeof(struct pkt) - MAX_MAC_LEN)
1777 ep->tstamp = vp->tstamp;
1778 ep->fstamp = vp->fstamp;
1779 ep->vallen = vp->vallen;
1782 * Copy value. If the data field is empty or zero length,
1783 * encode an empty value with length zero.
1786 if (vallen > 0 && vp->ptr != NULL) {
1789 ep->pkt[i + j++] = 0;
1790 memcpy(&ep->pkt[i], vp->ptr, vallen);
1795 * Copy signature. If the signature field is empty or zero
1796 * length, encode an empty signature with length zero.
1798 ep->pkt[i++] = vp->siglen;
1799 if (siglen > 0 && vp->sig != NULL) {
1802 ep->pkt[i + j++] = 0;
1803 memcpy(&ep->pkt[i], vp->sig, siglen);
1804 /* i += j; */ /* We don't use i after this */
1806 opcode = ntohl(ep->opcode);
1807 ep->opcode = htonl((opcode & 0xffff0000) | len);
1808 ENSURE(len <= MAX_VALLEN);
1814 * crypto_update - compute new public value and sign extension fields
1816 * This routine runs periodically, like once a day, and when something
1817 * changes. It updates the timestamps on three value structures and one
1818 * value structure list, then signs all the structures:
1820 * hostval host name (not signed)
1822 * cinfo certificate info/value list
1823 * tai_leap leap values
1825 * Filestamps are proventic data, so this routine runs only when the
1826 * host is synchronized to a proventicated source. Thus, the timestamp
1827 * is proventic and can be used to deflect clogging attacks.
1829 * Returns void (no errors)
1834 EVP_MD_CTX *ctx; /* message digest context */
1835 struct cert_info *cp; /* certificate info/value */
1836 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1839 leap_result_t leap_data;
1841 hostval.tstamp = htonl(crypto_time());
1842 if (hostval.tstamp == 0)
1845 ctx = EVP_MD_CTX_new();
1848 * Sign public key and timestamps. The filestamp is derived from
1849 * the host key file extension from wherever the file was
1852 if (pubkey.vallen != 0) {
1853 pubkey.tstamp = hostval.tstamp;
1855 if (pubkey.sig == NULL)
1856 pubkey.sig = emalloc(sign_siglen);
1857 EVP_SignInit(ctx, sign_digest);
1858 EVP_SignUpdate(ctx, (u_char *)&pubkey, 12);
1859 EVP_SignUpdate(ctx, pubkey.ptr, ntohl(pubkey.vallen));
1860 if (EVP_SignFinal(ctx, pubkey.sig, &len, sign_pkey)) {
1861 INSIST(len <= sign_siglen);
1862 pubkey.siglen = htonl(len);
1867 * Sign certificates and timestamps. The filestamp is derived
1868 * from the certificate file extension from wherever the file
1869 * was generated. Note we do not throw expired certificates
1870 * away; they may have signed younger ones.
1872 for (cp = cinfo; cp != NULL; cp = cp->link) {
1873 cp->cert.tstamp = hostval.tstamp;
1874 cp->cert.siglen = 0;
1875 if (cp->cert.sig == NULL)
1876 cp->cert.sig = emalloc(sign_siglen);
1877 EVP_SignInit(ctx, sign_digest);
1878 EVP_SignUpdate(ctx, (u_char *)&cp->cert, 12);
1879 EVP_SignUpdate(ctx, cp->cert.ptr,
1880 ntohl(cp->cert.vallen));
1881 if (EVP_SignFinal(ctx, cp->cert.sig, &len, sign_pkey)) {
1882 INSIST(len <= sign_siglen);
1883 cp->cert.siglen = htonl(len);
1888 * Sign leapseconds values and timestamps. Note it is not an
1889 * error to return null values.
1891 tai_leap.tstamp = hostval.tstamp;
1892 tai_leap.fstamp = hostval.fstamp;
1894 /* Get the leap second era. We might need a full lookup early
1895 * after start, when the cache is not yet loaded.
1897 leapsec_frame(&leap_data);
1898 if ( ! memcmp(&leap_data.ebase, &leap_data.ttime, sizeof(vint64))) {
1899 time_t now = time(NULL);
1900 uint32_t nowntp = (uint32_t)now + JAN_1970;
1901 leapsec_query(&leap_data, nowntp, &now);
1904 /* Create the data block. The protocol does not work without. */
1905 len = 3 * sizeof(u_int32);
1906 if (tai_leap.ptr == NULL || ntohl(tai_leap.vallen) != len) {
1908 tai_leap.ptr = emalloc(len);
1909 tai_leap.vallen = htonl(len);
1911 ptr = (u_int32 *)tai_leap.ptr;
1912 if (leap_data.tai_offs > 10) {
1913 /* create a TAI / leap era block. The end time is a
1914 * fake -- maybe we can do better.
1916 ptr[0] = htonl(leap_data.tai_offs);
1917 ptr[1] = htonl(leap_data.ebase.d_s.lo);
1918 if (leap_data.ttime.d_s.hi >= 0)
1919 ptr[2] = htonl(leap_data.ttime.D_s.lo + 7*86400);
1921 ptr[2] = htonl(leap_data.ebase.D_s.lo + 25*86400);
1923 /* no leap era available */
1924 memset(ptr, 0, len);
1926 if (tai_leap.sig == NULL)
1927 tai_leap.sig = emalloc(sign_siglen);
1928 EVP_SignInit(ctx, sign_digest);
1929 EVP_SignUpdate(ctx, (u_char *)&tai_leap, 12);
1930 EVP_SignUpdate(ctx, tai_leap.ptr, len);
1931 if (EVP_SignFinal(ctx, tai_leap.sig, &len, sign_pkey)) {
1932 INSIST(len <= sign_siglen);
1933 tai_leap.siglen = htonl(len);
1935 crypto_flags |= CRYPTO_FLAG_TAI;
1937 snprintf(statstr, sizeof(statstr), "signature update ts %u",
1938 ntohl(hostval.tstamp));
1939 record_crypto_stats(NULL, statstr);
1940 DPRINTF(1, ("crypto_update: %s\n", statstr));
1941 EVP_MD_CTX_free(ctx);
1945 * crypto_update_taichange - eventually trigger crypto_update
1947 * This is called when a change in 'sys_tai' is detected. This will
1948 * happen shortly after a leap second is detected, but unhappily also
1949 * early after system start; also, the crypto stuff might be unused and
1950 * an unguarded call to crypto_update() causes a crash.
1952 * This function makes sure that there already *is* a valid crypto block
1953 * for the use with autokey, and only calls 'crypto_update()' if it can
1956 * Returns void (no errors)
1959 crypto_update_taichange(void)
1961 static const u_int len = 3 * sizeof(u_int32);
1963 /* check if the signing digest algo is available */
1964 if (sign_digest == NULL || sign_pkey == NULL)
1967 /* check size of TAI extension block */
1968 if (tai_leap.ptr == NULL || ntohl(tai_leap.vallen) != len)
1971 /* crypto_update should at least not crash here! */
1976 * value_free - free value structure components.
1978 * Returns void (no errors)
1982 struct value *vp /* value structure */
1985 if (vp->ptr != NULL)
1987 if (vp->sig != NULL)
1989 memset(vp, 0, sizeof(struct value));
1994 * crypto_time - returns current NTP time.
1996 * Returns NTP seconds if in synch, 0 otherwise
2001 l_fp tstamp; /* NTP time */
2004 if (sys_leap != LEAP_NOTINSYNC)
2005 get_systime(&tstamp);
2006 return (tstamp.l_ui);
2011 * asn_to_calendar - convert ASN1_TIME time structure to struct calendar.
2017 const ASN1_TIME *asn1time, /* pointer to ASN1_TIME structure */
2018 struct calendar *pjd /* pointer to result */
2021 size_t len; /* length of ASN1_TIME string */
2022 char v[24]; /* writable copy of ASN1_TIME string */
2023 unsigned long temp; /* result from strtoul */
2026 * Extract time string YYMMDDHHMMSSZ from ASN1 time structure.
2027 * Or YYYYMMDDHHMMSSZ.
2028 * Note that the YY, MM, DD fields start with one, the HH, MM,
2029 * SS fields start with zero and the Z character is ignored.
2030 * Also note that two-digit years less than 50 map to years greater than
2031 * 100. Dontcha love ASN.1? Better than MIL-188.
2033 len = asn1time->length;
2034 REQUIRE(len < sizeof(v));
2035 (void)strncpy(v, (char *)(asn1time->data), len);
2037 temp = strtoul(v+len-3, NULL, 10);
2041 temp = strtoul(v+len-5, NULL, 10);
2045 temp = strtoul(v+len-7, NULL, 10);
2049 temp = strtoul(v+len-9, NULL, 10);
2050 pjd->monthday = temp;
2053 temp = strtoul(v+len-11, NULL, 10);
2057 temp = strtoul(v, NULL, 10);
2058 /* handle two-digit years */
2065 pjd->yearday = pjd->weekday = 0;
2071 * bigdig() - compute a BIGNUM MD5 hash of a BIGNUM number.
2073 * Returns void (no errors)
2077 BIGNUM *bn, /* BIGNUM * from */
2078 BIGNUM *bk /* BIGNUM * to */
2081 EVP_MD_CTX *ctx; /* message digest context */
2082 u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
2083 u_char *ptr; /* a BIGNUM as binary string */
2086 len = BN_num_bytes(bn);
2089 ctx = EVP_MD_CTX_new();
2090 EVP_DigestInit(ctx, EVP_md5());
2091 EVP_DigestUpdate(ctx, ptr, len);
2092 EVP_DigestFinal(ctx, dgst, &len);
2093 EVP_MD_CTX_free(ctx);
2094 BN_bin2bn(dgst, len, bk);
2100 ***********************************************************************
2102 * The following routines implement the Schnorr (IFF) identity scheme *
2104 ***********************************************************************
2106 * The Schnorr (IFF) identity scheme is intended for use when
2107 * certificates are generated by some other trusted certificate
2108 * authority and the certificate cannot be used to convey public
2109 * parameters. There are two kinds of files: encrypted server files that
2110 * contain private and public values and nonencrypted client files that
2111 * contain only public values. New generations of server files must be
2112 * securely transmitted to all servers of the group; client files can be
2113 * distributed by any means. The scheme is self contained and
2114 * independent of new generations of host keys, sign keys and
2117 * The IFF values hide in a DSA cuckoo structure which uses the same
2118 * parameters. The values are used by an identity scheme based on DSA
2119 * cryptography and described in Stimson p. 285. The p is a 512-bit
2120 * prime, g a generator of Zp* and q a 160-bit prime that divides p - 1
2121 * and is a qth root of 1 mod p; that is, g^q = 1 mod p. The TA rolls a
2122 * private random group key b (0 < b < q) and public key v = g^b, then
2123 * sends (p, q, g, b) to the servers and (p, q, g, v) to the clients.
2124 * Alice challenges Bob to confirm identity using the protocol described
2129 * The scheme goes like this. Both Alice and Bob have the public primes
2130 * p, q and generator g. The TA gives private key b to Bob and public
2133 * Alice rolls new random challenge r (o < r < q) and sends to Bob in
2134 * the IFF request message. Bob rolls new random k (0 < k < q), then
2135 * computes y = k + b r mod q and x = g^k mod p and sends (y, hash(x))
2136 * to Alice in the response message. Besides making the response
2137 * shorter, the hash makes it effectivey impossible for an intruder to
2138 * solve for b by observing a number of these messages.
2140 * Alice receives the response and computes g^y v^r mod p. After a bit
2141 * of algebra, this simplifies to g^k. If the hash of this result
2142 * matches hash(x), Alice knows that Bob has the group key b. The signed
2143 * response binds this knowledge to Bob's private key and the public key
2144 * previously received in his certificate.
2146 * crypto_alice - construct Alice's challenge in IFF scheme
2150 * XEVNT_ID bad or missing group key
2151 * XEVNT_PUB bad or missing public key
2155 struct peer *peer, /* peer pointer */
2156 struct value *vp /* value pointer */
2159 DSA *dsa; /* IFF parameters */
2160 BN_CTX *bctx; /* BIGNUM context */
2161 EVP_MD_CTX *ctx; /* signature context */
2167 * The identity parameters must have correct format and content.
2169 if (peer->ident_pkey == NULL) {
2170 msyslog(LOG_NOTICE, "crypto_alice: scheme unavailable");
2174 if ((dsa = EVP_PKEY_get0_DSA(peer->ident_pkey->pkey)) == NULL) {
2175 msyslog(LOG_NOTICE, "crypto_alice: defective key");
2180 * Roll new random r (0 < r < q).
2182 if (peer->iffval != NULL)
2183 BN_free(peer->iffval);
2184 peer->iffval = BN_new();
2185 DSA_get0_pqg(dsa, NULL, &q, NULL);
2186 len = BN_num_bytes(q);
2187 BN_rand(peer->iffval, len * 8, -1, 1); /* r mod q*/
2188 bctx = BN_CTX_new();
2189 BN_mod(peer->iffval, peer->iffval, q, bctx);
2193 * Sign and send to Bob. The filestamp is from the local file.
2195 memset(vp, 0, sizeof(struct value));
2196 tstamp = crypto_time();
2197 vp->tstamp = htonl(tstamp);
2198 vp->fstamp = htonl(peer->ident_pkey->fstamp);
2199 vp->vallen = htonl(len);
2200 vp->ptr = emalloc(len);
2201 BN_bn2bin(peer->iffval, vp->ptr);
2205 vp->sig = emalloc(sign_siglen);
2206 ctx = EVP_MD_CTX_new();
2207 EVP_SignInit(ctx, sign_digest);
2208 EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
2209 EVP_SignUpdate(ctx, vp->ptr, len);
2210 if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
2211 INSIST(len <= sign_siglen);
2212 vp->siglen = htonl(len);
2214 EVP_MD_CTX_free(ctx);
2220 * crypto_bob - construct Bob's response to Alice's challenge
2224 * XEVNT_ERR protocol error
2225 * XEVNT_ID bad or missing group key
2229 struct exten *ep, /* extension pointer */
2230 struct value *vp /* value pointer */
2233 DSA *dsa; /* IFF parameters */
2234 DSA_SIG *sdsa; /* DSA signature context fake */
2235 BN_CTX *bctx; /* BIGNUM context */
2236 EVP_MD_CTX *ctx; /* signature context */
2237 tstamp_t tstamp; /* NTP timestamp */
2238 BIGNUM *bn, *bk, *r;
2240 u_int len; /* extension field value length */
2241 const BIGNUM *p, *q, *g;
2242 const BIGNUM *priv_key;
2245 * If the IFF parameters are not valid, something awful
2246 * happened or we are being tormented.
2248 if (iffkey_info == NULL) {
2249 msyslog(LOG_NOTICE, "crypto_bob: scheme unavailable");
2252 dsa = EVP_PKEY_get0_DSA(iffkey_info->pkey);
2253 DSA_get0_pqg(dsa, &p, &q, &g);
2254 DSA_get0_key(dsa, NULL, &priv_key);
2257 * Extract r from the challenge.
2259 len = exten_payload_size(ep);
2260 if (len == 0 || len > MAX_VALLEN)
2262 if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2263 msyslog(LOG_ERR, "crypto_bob: %s",
2264 ERR_error_string(ERR_get_error(), NULL));
2269 * Bob rolls random k (0 < k < q), computes y = k + b r mod q
2270 * and x = g^k mod p, then sends (y, hash(x)) to Alice.
2272 bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2273 sdsa = DSA_SIG_new();
2274 BN_rand(bk, len * 8, -1, 1); /* k */
2275 BN_mod_mul(bn, priv_key, r, q, bctx); /* b r mod q */
2277 BN_mod(bn, bn, q, bctx); /* k + b r mod q */
2278 BN_mod_exp(bk, g, bk, p, bctx); /* g^k mod p */
2280 DSA_SIG_set0(sdsa, bn, bk);
2285 DSA_print_fp(stdout, dsa, 0);
2289 * Encode the values in ASN.1 and sign. The filestamp is from
2292 len = i2d_DSA_SIG(sdsa, NULL);
2294 msyslog(LOG_ERR, "crypto_bob: %s",
2295 ERR_error_string(ERR_get_error(), NULL));
2299 if (len > MAX_VALLEN) {
2300 msyslog(LOG_ERR, "crypto_bob: signature is too big: %u",
2305 memset(vp, 0, sizeof(struct value));
2306 tstamp = crypto_time();
2307 vp->tstamp = htonl(tstamp);
2308 vp->fstamp = htonl(iffkey_info->fstamp);
2309 vp->vallen = htonl(len);
2312 i2d_DSA_SIG(sdsa, &ptr);
2317 /* XXX: more validation to make sure the sign fits... */
2318 vp->sig = emalloc(sign_siglen);
2319 ctx = EVP_MD_CTX_new();
2320 EVP_SignInit(ctx, sign_digest);
2321 EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
2322 EVP_SignUpdate(ctx, vp->ptr, len);
2323 if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
2324 INSIST(len <= sign_siglen);
2325 vp->siglen = htonl(len);
2327 EVP_MD_CTX_free(ctx);
2333 * crypto_iff - verify Bob's response to Alice's challenge
2337 * XEVNT_FSP bad filestamp
2338 * XEVNT_ID bad or missing group key
2339 * XEVNT_PUB bad or missing public key
2343 struct exten *ep, /* extension pointer */
2344 struct peer *peer /* peer structure pointer */
2347 DSA *dsa; /* IFF parameters */
2348 BN_CTX *bctx; /* BIGNUM context */
2349 DSA_SIG *sdsa; /* DSA parameters */
2354 const BIGNUM *p, *g;
2355 const BIGNUM *r, *s;
2356 const BIGNUM *pub_key;
2359 * If the IFF parameters are not valid or no challenge was sent,
2360 * something awful happened or we are being tormented.
2362 if (peer->ident_pkey == NULL) {
2363 msyslog(LOG_NOTICE, "crypto_iff: scheme unavailable");
2366 if (ntohl(ep->fstamp) != peer->ident_pkey->fstamp) {
2367 msyslog(LOG_NOTICE, "crypto_iff: invalid filestamp %u",
2371 if ((dsa = EVP_PKEY_get0_DSA(peer->ident_pkey->pkey)) == NULL) {
2372 msyslog(LOG_NOTICE, "crypto_iff: defective key");
2375 if (peer->iffval == NULL) {
2376 msyslog(LOG_NOTICE, "crypto_iff: missing challenge");
2381 * Extract the k + b r and g^k values from the response.
2383 bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2384 len = ntohl(ep->vallen);
2385 ptr = (u_char *)ep->pkt;
2386 if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2387 BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
2388 msyslog(LOG_ERR, "crypto_iff: %s",
2389 ERR_error_string(ERR_get_error(), NULL));
2394 * Compute g^(k + b r) g^(q - b)r mod p.
2396 DSA_get0_key(dsa, &pub_key, NULL);
2397 DSA_get0_pqg(dsa, &p, NULL, &g);
2398 DSA_SIG_get0(sdsa, &r, &s);
2399 BN_mod_exp(bn, pub_key, peer->iffval, p, bctx);
2400 BN_mod_exp(bk, g, r, p, bctx);
2401 BN_mod_mul(bn, bn, bk, p, bctx);
2404 * Verify the hash of the result matches hash(x).
2407 temp = BN_cmp(bn, s);
2408 BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
2409 BN_free(peer->iffval);
2410 peer->iffval = NULL;
2415 msyslog(LOG_NOTICE, "crypto_iff: identity not verified");
2421 ***********************************************************************
2423 * The following routines implement the Guillou-Quisquater (GQ) *
2426 ***********************************************************************
2428 * The Guillou-Quisquater (GQ) identity scheme is intended for use when
2429 * the certificate can be used to convey public parameters. The scheme
2430 * uses a X509v3 certificate extension field do convey the public key of
2431 * a private key known only to servers. There are two kinds of files:
2432 * encrypted server files that contain private and public values and
2433 * nonencrypted client files that contain only public values. New
2434 * generations of server files must be securely transmitted to all
2435 * servers of the group; client files can be distributed by any means.
2436 * The scheme is self contained and independent of new generations of
2437 * host keys and sign keys. The scheme is self contained and independent
2438 * of new generations of host keys and sign keys.
2440 * The GQ parameters hide in a RSA cuckoo structure which uses the same
2441 * parameters. The values are used by an identity scheme based on RSA
2442 * cryptography and described in Stimson p. 300 (with errors). The 512-
2443 * bit public modulus is n = p q, where p and q are secret large primes.
2444 * The TA rolls private random group key b as RSA exponent. These values
2445 * are known to all group members.
2447 * When rolling new certificates, a server recomputes the private and
2448 * public keys. The private key u is a random roll, while the public key
2449 * is the inverse obscured by the group key v = (u^-1)^b. These values
2450 * replace the private and public keys normally generated by the RSA
2451 * scheme. Alice challenges Bob to confirm identity using the protocol
2456 * The scheme goes like this. Both Alice and Bob have the same modulus n
2457 * and some random b as the group key. These values are computed and
2458 * distributed in advance via secret means, although only the group key
2459 * b is truly secret. Each has a private random private key u and public
2460 * key (u^-1)^b, although not necessarily the same ones. Bob and Alice
2461 * can regenerate the key pair from time to time without affecting
2462 * operations. The public key is conveyed on the certificate in an
2463 * extension field; the private key is never revealed.
2465 * Alice rolls new random challenge r and sends to Bob in the GQ
2466 * request message. Bob rolls new random k, then computes y = k u^r mod
2467 * n and x = k^b mod n and sends (y, hash(x)) to Alice in the response
2468 * message. Besides making the response shorter, the hash makes it
2469 * effectivey impossible for an intruder to solve for b by observing
2470 * a number of these messages.
2472 * Alice receives the response and computes y^b v^r mod n. After a bit
2473 * of algebra, this simplifies to k^b. If the hash of this result
2474 * matches hash(x), Alice knows that Bob has the group key b. The signed
2475 * response binds this knowledge to Bob's private key and the public key
2476 * previously received in his certificate.
2478 * crypto_alice2 - construct Alice's challenge in GQ scheme
2482 * XEVNT_ID bad or missing group key
2483 * XEVNT_PUB bad or missing public key
2487 struct peer *peer, /* peer pointer */
2488 struct value *vp /* value pointer */
2491 RSA *rsa; /* GQ parameters */
2492 BN_CTX *bctx; /* BIGNUM context */
2493 EVP_MD_CTX *ctx; /* signature context */
2499 * The identity parameters must have correct format and content.
2501 if (peer->ident_pkey == NULL)
2504 if ((rsa = EVP_PKEY_get0_RSA(peer->ident_pkey->pkey)) == NULL) {
2505 msyslog(LOG_NOTICE, "crypto_alice2: defective key");
2510 * Roll new random r (0 < r < n).
2512 if (peer->iffval != NULL)
2513 BN_free(peer->iffval);
2514 peer->iffval = BN_new();
2515 RSA_get0_key(rsa, &n, NULL, NULL);
2516 len = BN_num_bytes(n);
2517 BN_rand(peer->iffval, len * 8, -1, 1); /* r mod n */
2518 bctx = BN_CTX_new();
2519 BN_mod(peer->iffval, peer->iffval, n, bctx);
2523 * Sign and send to Bob. The filestamp is from the local file.
2525 memset(vp, 0, sizeof(struct value));
2526 tstamp = crypto_time();
2527 vp->tstamp = htonl(tstamp);
2528 vp->fstamp = htonl(peer->ident_pkey->fstamp);
2529 vp->vallen = htonl(len);
2530 vp->ptr = emalloc(len);
2531 BN_bn2bin(peer->iffval, vp->ptr);
2535 vp->sig = emalloc(sign_siglen);
2536 ctx = EVP_MD_CTX_new();
2537 EVP_SignInit(ctx, sign_digest);
2538 EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
2539 EVP_SignUpdate(ctx, vp->ptr, len);
2540 if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
2541 INSIST(len <= sign_siglen);
2542 vp->siglen = htonl(len);
2544 EVP_MD_CTX_free(ctx);
2550 * crypto_bob2 - construct Bob's response to Alice's challenge
2554 * XEVNT_ERR protocol error
2555 * XEVNT_ID bad or missing group key
2559 struct exten *ep, /* extension pointer */
2560 struct value *vp /* value pointer */
2563 RSA *rsa; /* GQ parameters */
2564 DSA_SIG *sdsa; /* DSA parameters */
2565 BN_CTX *bctx; /* BIGNUM context */
2566 EVP_MD_CTX *ctx; /* signature context */
2567 tstamp_t tstamp; /* NTP timestamp */
2568 BIGNUM *r, *k, *g, *y;
2572 const BIGNUM *n, *p, *e;
2575 * If the GQ parameters are not valid, something awful
2576 * happened or we are being tormented.
2578 if (gqkey_info == NULL) {
2579 msyslog(LOG_NOTICE, "crypto_bob2: scheme unavailable");
2582 rsa = EVP_PKEY_get0_RSA(gqkey_info->pkey);
2583 RSA_get0_key(rsa, &n, &p, &e);
2586 * Extract r from the challenge.
2588 len = exten_payload_size(ep);
2589 if (len == 0 || len > MAX_VALLEN)
2591 if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2592 msyslog(LOG_ERR, "crypto_bob2: %s",
2593 ERR_error_string(ERR_get_error(), NULL));
2598 * Bob rolls random k (0 < k < n), computes y = k u^r mod n and
2599 * x = k^b mod n, then sends (y, hash(x)) to Alice.
2601 bctx = BN_CTX_new(); k = BN_new(); g = BN_new(); y = BN_new();
2602 sdsa = DSA_SIG_new();
2603 BN_rand(k, len * 8, -1, 1); /* k */
2604 BN_mod(k, k, n, bctx);
2605 BN_mod_exp(y, p, r, n, bctx); /* u^r mod n */
2606 BN_mod_mul(y, k, y, n, bctx); /* k u^r mod n */
2607 BN_mod_exp(g, k, e, n, bctx); /* k^b mod n */
2609 DSA_SIG_set0(sdsa, y, g);
2611 BN_free(r); BN_free(k);
2614 RSA_print_fp(stdout, rsa, 0);
2618 * Encode the values in ASN.1 and sign. The filestamp is from
2621 len = s_len = i2d_DSA_SIG(sdsa, NULL);
2623 msyslog(LOG_ERR, "crypto_bob2: %s",
2624 ERR_error_string(ERR_get_error(), NULL));
2628 memset(vp, 0, sizeof(struct value));
2629 tstamp = crypto_time();
2630 vp->tstamp = htonl(tstamp);
2631 vp->fstamp = htonl(gqkey_info->fstamp);
2632 vp->vallen = htonl(len);
2635 i2d_DSA_SIG(sdsa, &ptr);
2640 vp->sig = emalloc(sign_siglen);
2641 ctx = EVP_MD_CTX_new();
2642 EVP_SignInit(ctx, sign_digest);
2643 EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
2644 EVP_SignUpdate(ctx, vp->ptr, len);
2645 if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
2646 INSIST(len <= sign_siglen);
2647 vp->siglen = htonl(len);
2649 EVP_MD_CTX_free(ctx);
2655 * crypto_gq - verify Bob's response to Alice's challenge
2659 * XEVNT_ERR protocol error
2660 * XEVNT_FSP bad filestamp
2661 * XEVNT_ID bad or missing group keys
2662 * XEVNT_PUB bad or missing public key
2666 struct exten *ep, /* extension pointer */
2667 struct peer *peer /* peer structure pointer */
2670 RSA *rsa; /* GQ parameters */
2671 BN_CTX *bctx; /* BIGNUM context */
2672 DSA_SIG *sdsa; /* RSA signature context fake */
2677 const BIGNUM *n, *e;
2678 const BIGNUM *r, *s;
2681 * If the GQ parameters are not valid or no challenge was sent,
2682 * something awful happened or we are being tormented. Note that
2683 * the filestamp on the local key file can be greater than on
2684 * the remote parameter file if the keys have been refreshed.
2686 if (peer->ident_pkey == NULL) {
2687 msyslog(LOG_NOTICE, "crypto_gq: scheme unavailable");
2690 if (ntohl(ep->fstamp) < peer->ident_pkey->fstamp) {
2691 msyslog(LOG_NOTICE, "crypto_gq: invalid filestamp %u",
2695 if ((rsa = EVP_PKEY_get0_RSA(peer->ident_pkey->pkey)) == NULL) {
2696 msyslog(LOG_NOTICE, "crypto_gq: defective key");
2699 RSA_get0_key(rsa, &n, NULL, &e);
2700 if (peer->iffval == NULL) {
2701 msyslog(LOG_NOTICE, "crypto_gq: missing challenge");
2706 * Extract the y = k u^r and hash(x = k^b) values from the
2709 bctx = BN_CTX_new(); y = BN_new(); v = BN_new();
2710 len = ntohl(ep->vallen);
2711 ptr = (u_char *)ep->pkt;
2712 if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2713 BN_CTX_free(bctx); BN_free(y); BN_free(v);
2714 msyslog(LOG_ERR, "crypto_gq: %s",
2715 ERR_error_string(ERR_get_error(), NULL));
2718 DSA_SIG_get0(sdsa, &r, &s);
2721 * Compute v^r y^b mod n.
2723 if (peer->grpkey == NULL) {
2724 msyslog(LOG_NOTICE, "crypto_gq: missing group key");
2727 BN_mod_exp(v, peer->grpkey, peer->iffval, n, bctx);
2729 BN_mod_exp(y, r, e, n, bctx); /* y^b mod n */
2730 BN_mod_mul(y, v, y, n, bctx); /* v^r y^b mod n */
2733 * Verify the hash of the result matches hash(x).
2736 temp = BN_cmp(y, s);
2737 BN_CTX_free(bctx); BN_free(y); BN_free(v);
2738 BN_free(peer->iffval);
2739 peer->iffval = NULL;
2744 msyslog(LOG_NOTICE, "crypto_gq: identity not verified");
2750 ***********************************************************************
2752 * The following routines implement the Mu-Varadharajan (MV) identity *
2755 ***********************************************************************
2757 * The Mu-Varadharajan (MV) cryptosystem was originally intended when
2758 * servers broadcast messages to clients, but clients never send
2759 * messages to servers. There is one encryption key for the server and a
2760 * separate decryption key for each client. It operated something like a
2761 * pay-per-view satellite broadcasting system where the session key is
2762 * encrypted by the broadcaster and the decryption keys are held in a
2763 * tamperproof set-top box.
2765 * The MV parameters and private encryption key hide in a DSA cuckoo
2766 * structure which uses the same parameters, but generated in a
2767 * different way. The values are used in an encryption scheme similar to
2768 * El Gamal cryptography and a polynomial formed from the expansion of
2769 * product terms (x - x[j]), as described in Mu, Y., and V.
2770 * Varadharajan: Robust and Secure Broadcasting, Proc. Indocrypt 2001,
2771 * 223-231. The paper has significant errors and serious omissions.
2773 * Let q be the product of n distinct primes s1[j] (j = 1...n), where
2774 * each s1[j] has m significant bits. Let p be a prime p = 2 * q + 1, so
2775 * that q and each s1[j] divide p - 1 and p has M = n * m + 1
2776 * significant bits. Let g be a generator of Zp; that is, gcd(g, p - 1)
2777 * = 1 and g^q = 1 mod p. We do modular arithmetic over Zq and then
2778 * project into Zp* as exponents of g. Sometimes we have to compute an
2779 * inverse b^-1 of random b in Zq, but for that purpose we require
2780 * gcd(b, q) = 1. We expect M to be in the 500-bit range and n
2781 * relatively small, like 30. These are the parameters of the scheme and
2782 * they are expensive to compute.
2784 * We set up an instance of the scheme as follows. A set of random
2785 * values x[j] mod q (j = 1...n), are generated as the zeros of a
2786 * polynomial of order n. The product terms (x - x[j]) are expanded to
2787 * form coefficients a[i] mod q (i = 0...n) in powers of x. These are
2788 * used as exponents of the generator g mod p to generate the private
2789 * encryption key A. The pair (gbar, ghat) of public server keys and the
2790 * pairs (xbar[j], xhat[j]) (j = 1...n) of private client keys are used
2791 * to construct the decryption keys. The devil is in the details.
2793 * This routine generates a private server encryption file including the
2794 * private encryption key E and partial decryption keys gbar and ghat.
2795 * It then generates public client decryption files including the public
2796 * keys xbar[j] and xhat[j] for each client j. The partial decryption
2797 * files are used to compute the inverse of E. These values are suitably
2798 * blinded so secrets are not revealed.
2800 * The distinguishing characteristic of this scheme is the capability to
2801 * revoke keys. Included in the calculation of E, gbar and ghat is the
2802 * product s = prod(s1[j]) (j = 1...n) above. If the factor s1[j] is
2803 * subsequently removed from the product and E, gbar and ghat
2804 * recomputed, the jth client will no longer be able to compute E^-1 and
2805 * thus unable to decrypt the messageblock.
2809 * The scheme goes like this. Bob has the server values (p, E, q, gbar,
2810 * ghat) and Alice has the client values (p, xbar, xhat).
2812 * Alice rolls new random nonce r mod p and sends to Bob in the MV
2813 * request message. Bob rolls random nonce k mod q, encrypts y = r E^k
2814 * mod p and sends (y, gbar^k, ghat^k) to Alice.
2816 * Alice receives the response and computes the inverse (E^k)^-1 from
2817 * the partial decryption keys gbar^k, ghat^k, xbar and xhat. She then
2818 * decrypts y and verifies it matches the original r. The signed
2819 * response binds this knowledge to Bob's private key and the public key
2820 * previously received in his certificate.
2822 * crypto_alice3 - construct Alice's challenge in MV scheme
2826 * XEVNT_ID bad or missing group key
2827 * XEVNT_PUB bad or missing public key
2831 struct peer *peer, /* peer pointer */
2832 struct value *vp /* value pointer */
2835 DSA *dsa; /* MV parameters */
2836 BN_CTX *bctx; /* BIGNUM context */
2837 EVP_MD_CTX *ctx; /* signature context */
2843 * The identity parameters must have correct format and content.
2845 if (peer->ident_pkey == NULL)
2848 if ((dsa = EVP_PKEY_get0_DSA(peer->ident_pkey->pkey)) == NULL) {
2849 msyslog(LOG_NOTICE, "crypto_alice3: defective key");
2852 DSA_get0_pqg(dsa, &p, NULL, NULL);
2855 * Roll new random r (0 < r < q).
2857 if (peer->iffval != NULL)
2858 BN_free(peer->iffval);
2859 peer->iffval = BN_new();
2860 len = BN_num_bytes(p);
2861 BN_rand(peer->iffval, len * 8, -1, 1); /* r mod p */
2862 bctx = BN_CTX_new();
2863 BN_mod(peer->iffval, peer->iffval, p, bctx);
2867 * Sign and send to Bob. The filestamp is from the local file.
2869 memset(vp, 0, sizeof(struct value));
2870 tstamp = crypto_time();
2871 vp->tstamp = htonl(tstamp);
2872 vp->fstamp = htonl(peer->ident_pkey->fstamp);
2873 vp->vallen = htonl(len);
2874 vp->ptr = emalloc(len);
2875 BN_bn2bin(peer->iffval, vp->ptr);
2879 vp->sig = emalloc(sign_siglen);
2880 ctx = EVP_MD_CTX_new();
2881 EVP_SignInit(ctx, sign_digest);
2882 EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
2883 EVP_SignUpdate(ctx, vp->ptr, len);
2884 if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
2885 INSIST(len <= sign_siglen);
2886 vp->siglen = htonl(len);
2888 EVP_MD_CTX_free(ctx);
2894 * crypto_bob3 - construct Bob's response to Alice's challenge
2898 * XEVNT_ERR protocol error
2902 struct exten *ep, /* extension pointer */
2903 struct value *vp /* value pointer */
2906 DSA *dsa; /* MV parameters */
2907 DSA *sdsa; /* DSA signature context fake */
2908 BN_CTX *bctx; /* BIGNUM context */
2909 EVP_MD_CTX *ctx; /* signature context */
2910 tstamp_t tstamp; /* NTP timestamp */
2914 const BIGNUM *p, *q, *g;
2915 const BIGNUM *pub_key, *priv_key;
2916 BIGNUM *sp, *sq, *sg;
2919 * If the MV parameters are not valid, something awful
2920 * happened or we are being tormented.
2922 if (mvkey_info == NULL) {
2923 msyslog(LOG_NOTICE, "crypto_bob3: scheme unavailable");
2926 dsa = EVP_PKEY_get0_DSA(mvkey_info->pkey);
2927 DSA_get0_pqg(dsa, &p, &q, &g);
2928 DSA_get0_key(dsa, &pub_key, &priv_key);
2931 * Extract r from the challenge.
2933 len = exten_payload_size(ep);
2934 if (len == 0 || len > MAX_VALLEN)
2936 if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2937 msyslog(LOG_ERR, "crypto_bob3: %s",
2938 ERR_error_string(ERR_get_error(), NULL));
2943 * Bob rolls random k (0 < k < q), making sure it is not a
2944 * factor of q. He then computes y = r A^k and sends (y, gbar^k,
2945 * and ghat^k) to Alice.
2947 bctx = BN_CTX_new(); k = BN_new(); u = BN_new();
2949 sp = BN_new(); sq = BN_new(); sg = BN_new();
2951 BN_rand(k, BN_num_bits(q), 0, 0);
2952 BN_mod(k, k, q, bctx);
2953 BN_gcd(u, k, q, bctx);
2957 BN_mod_exp(u, g, k, p, bctx); /* A^k r */
2958 BN_mod_mul(sp, u, r, p, bctx);
2959 BN_mod_exp(sq, priv_key, k, p, bctx); /* gbar */
2960 BN_mod_exp(sg, pub_key, k, p, bctx); /* ghat */
2961 DSA_set0_key(sdsa, BN_dup(pub_key), NULL);
2962 DSA_set0_pqg(sdsa, sp, sq, sg);
2963 BN_CTX_free(bctx); BN_free(k); BN_free(r); BN_free(u);
2966 DSA_print_fp(stdout, sdsa, 0);
2970 * Encode the values in ASN.1 and sign. The filestamp is from
2973 memset(vp, 0, sizeof(struct value));
2974 tstamp = crypto_time();
2975 vp->tstamp = htonl(tstamp);
2976 vp->fstamp = htonl(mvkey_info->fstamp);
2977 len = i2d_DSAparams(sdsa, NULL);
2979 msyslog(LOG_ERR, "crypto_bob3: %s",
2980 ERR_error_string(ERR_get_error(), NULL));
2984 vp->vallen = htonl(len);
2987 i2d_DSAparams(sdsa, &ptr);
2992 vp->sig = emalloc(sign_siglen);
2993 ctx = EVP_MD_CTX_new();
2994 EVP_SignInit(ctx, sign_digest);
2995 EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
2996 EVP_SignUpdate(ctx, vp->ptr, len);
2997 if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
2998 INSIST(len <= sign_siglen);
2999 vp->siglen = htonl(len);
3001 EVP_MD_CTX_free(ctx);
3007 * crypto_mv - verify Bob's response to Alice's challenge
3011 * XEVNT_ERR protocol error
3012 * XEVNT_FSP bad filestamp
3013 * XEVNT_ID bad or missing group key
3014 * XEVNT_PUB bad or missing public key
3018 struct exten *ep, /* extension pointer */
3019 struct peer *peer /* peer structure pointer */
3022 DSA *dsa; /* MV parameters */
3023 DSA *sdsa; /* DSA parameters */
3024 BN_CTX *bctx; /* BIGNUM context */
3030 const BIGNUM *pub_key, *priv_key;
3031 const BIGNUM *sp, *sq, *sg;
3034 * If the MV parameters are not valid or no challenge was sent,
3035 * something awful happened or we are being tormented.
3037 if (peer->ident_pkey == NULL) {
3038 msyslog(LOG_NOTICE, "crypto_mv: scheme unavailable");
3041 if (ntohl(ep->fstamp) != peer->ident_pkey->fstamp) {
3042 msyslog(LOG_NOTICE, "crypto_mv: invalid filestamp %u",
3046 if ((dsa = EVP_PKEY_get0_DSA(peer->ident_pkey->pkey)) == NULL) {
3047 msyslog(LOG_NOTICE, "crypto_mv: defective key");
3050 DSA_get0_pqg(dsa, &p, NULL, NULL);
3051 DSA_get0_key(dsa, &pub_key, &priv_key);
3052 if (peer->iffval == NULL) {
3053 msyslog(LOG_NOTICE, "crypto_mv: missing challenge");
3058 * Extract the y, gbar and ghat values from the response.
3060 bctx = BN_CTX_new(); k = BN_new(); u = BN_new(); v = BN_new();
3061 len = ntohl(ep->vallen);
3062 ptr = (u_char *)ep->pkt;
3063 if ((sdsa = d2i_DSAparams(NULL, &ptr, len)) == NULL) {
3064 msyslog(LOG_ERR, "crypto_mv: %s",
3065 ERR_error_string(ERR_get_error(), NULL));
3068 DSA_get0_pqg(sdsa, &sp, &sq, &sg);
3071 * Compute (gbar^xhat ghat^xbar) mod p.
3073 BN_mod_exp(u, sq, pub_key, p, bctx);
3074 BN_mod_exp(v, sg, priv_key, p, bctx);
3075 BN_mod_mul(u, u, v, p, bctx);
3076 BN_mod_mul(u, u, sp, p, bctx);
3079 * The result should match r.
3081 temp = BN_cmp(u, peer->iffval);
3082 BN_CTX_free(bctx); BN_free(k); BN_free(u); BN_free(v);
3083 BN_free(peer->iffval);
3084 peer->iffval = NULL;
3089 msyslog(LOG_NOTICE, "crypto_mv: identity not verified");
3095 ***********************************************************************
3097 * The following routines are used to manipulate certificates *
3099 ***********************************************************************
3102 * cert_sign - sign x509 certificate equest and update value structure.
3104 * The certificate request includes a copy of the host certificate,
3105 * which includes the version number, subject name and public key of the
3106 * host. The resulting certificate includes these values plus the
3107 * serial number, issuer name and valid interval of the server. The
3108 * valid interval extends from the current time to the same time one
3109 * year hence. This may extend the life of the signed certificate beyond
3110 * that of the signer certificate.
3112 * It is convenient to use the NTP seconds of the current time as the
3113 * serial number. In the value structure the timestamp is the current
3114 * time and the filestamp is taken from the extension field. Note this
3115 * routine is called only when the client clock is synchronized to a
3116 * proventic source, so timestamp comparisons are valid.
3118 * The host certificate is valid from the time it was generated for a
3119 * period of one year. A signed certificate is valid from the time of
3120 * signature for a period of one year, but only the host certificate (or
3121 * sign certificate if used) is actually used to encrypt and decrypt
3122 * signatures. The signature trail is built from the client via the
3123 * intermediate servers to the trusted server. Each signature on the
3124 * trail must be valid at the time of signature, but it could happen
3125 * that a signer certificate expire before the signed certificate, which
3126 * remains valid until its expiration.
3130 * XEVNT_CRT bad or missing certificate
3131 * XEVNT_PER host certificate expired
3132 * XEVNT_PUB bad or missing public key
3133 * XEVNT_VFY certificate not verified
3137 struct exten *ep, /* extension field pointer */
3138 struct value *vp /* value pointer */
3141 X509 *req; /* X509 certificate request */
3142 X509 *cert; /* X509 certificate */
3143 X509_EXTENSION *ext; /* certificate extension */
3144 ASN1_INTEGER *serial; /* serial number */
3145 X509_NAME *subj; /* distinguished (common) name */
3146 EVP_PKEY *pkey; /* public key */
3147 EVP_MD_CTX *ctx; /* message digest context */
3148 tstamp_t tstamp; /* NTP timestamp */
3149 struct calendar tscal;
3156 * Decode ASN.1 objects and construct certificate structure.
3157 * Make sure the system clock is synchronized to a proventic
3160 tstamp = crypto_time();
3164 len = exten_payload_size(ep);
3165 if (len == 0 || len > MAX_VALLEN)
3167 cptr = (void *)ep->pkt;
3168 if ((req = d2i_X509(NULL, &cptr, len)) == NULL) {
3169 msyslog(LOG_ERR, "cert_sign: %s",
3170 ERR_error_string(ERR_get_error(), NULL));
3174 * Extract public key and check for errors.
3176 if ((pkey = X509_get_pubkey(req)) == NULL) {
3177 msyslog(LOG_ERR, "cert_sign: %s",
3178 ERR_error_string(ERR_get_error(), NULL));
3184 * Generate X509 certificate signed by this server. If this is a
3185 * trusted host, the issuer name is the group name; otherwise,
3186 * it is the host name. Also copy any extensions that might be
3190 X509_set_version(cert, X509_get_version(req));
3191 serial = ASN1_INTEGER_new();
3192 ASN1_INTEGER_set(serial, tstamp);
3193 X509_set_serialNumber(cert, serial);
3194 X509_gmtime_adj(X509_getm_notBefore(cert), 0L);
3195 X509_gmtime_adj(X509_getm_notAfter(cert), YEAR);
3196 subj = X509_get_issuer_name(cert);
3197 X509_NAME_add_entry_by_txt(subj, "commonName", MBSTRING_ASC,
3198 hostval.ptr, strlen((const char *)hostval.ptr), -1, 0);
3199 subj = X509_get_subject_name(req);
3200 X509_set_subject_name(cert, subj);
3201 X509_set_pubkey(cert, pkey);
3202 temp = X509_get_ext_count(req);
3203 for (i = 0; i < temp; i++) {
3204 ext = X509_get_ext(req, i);
3205 INSIST(X509_add_ext(cert, ext, -1));
3210 * Sign and verify the client certificate, but only if the host
3211 * certificate has not expired.
3213 (void)ntpcal_ntp_to_date(&tscal, tstamp, NULL);
3214 if ((calcomp(&tscal, &(cert_host->first)) < 0)
3215 || (calcomp(&tscal, &(cert_host->last)) > 0)) {
3219 X509_sign(cert, sign_pkey, sign_digest);
3220 if (X509_verify(cert, sign_pkey) <= 0) {
3221 msyslog(LOG_ERR, "cert_sign: %s",
3222 ERR_error_string(ERR_get_error(), NULL));
3226 len = i2d_X509(cert, NULL);
3229 * Build and sign the value structure. We have to sign it here,
3230 * since the response has to be returned right away. This is a
3233 memset(vp, 0, sizeof(struct value));
3234 vp->tstamp = htonl(tstamp);
3235 vp->fstamp = ep->fstamp;
3236 vp->vallen = htonl(len);
3237 vp->ptr = emalloc(len);
3239 i2d_X509(cert, (unsigned char **)(intptr_t)&ptr);
3242 vp->sig = emalloc(sign_siglen);
3243 ctx = EVP_MD_CTX_new();
3244 EVP_SignInit(ctx, sign_digest);
3245 EVP_SignUpdate(ctx, (u_char *)vp, 12);
3246 EVP_SignUpdate(ctx, vp->ptr, len);
3247 if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
3248 INSIST(len <= sign_siglen);
3249 vp->siglen = htonl(len);
3251 EVP_MD_CTX_free(ctx);
3255 X509_print_fp(stdout, cert);
3263 * cert_install - install certificate in certificate cache
3265 * This routine encodes an extension field into a certificate info/value
3266 * structure. It searches the certificate list for duplicates and
3267 * expunges whichever is older. Finally, it inserts this certificate
3268 * first on the list.
3270 * Returns certificate info pointer if valid, NULL if not.
3274 struct exten *ep, /* cert info/value */
3275 struct peer *peer /* peer structure */
3278 struct cert_info *cp, *xp, **zp;
3281 * Parse and validate the signed certificate. If valid,
3282 * construct the info/value structure; otherwise, scamper home
3285 if ((cp = cert_parse((u_char *)ep->pkt, (long)ntohl(ep->vallen),
3286 (tstamp_t)ntohl(ep->fstamp))) == NULL)
3290 * Scan certificate list looking for another certificate with
3291 * the same subject and issuer. If another is found with the
3292 * same or older filestamp, unlink it and return the goodies to
3293 * the heap. If another is found with a later filestamp, discard
3294 * the new one and leave the building with the old one.
3296 * Make a note to study this issue again. An earlier certificate
3297 * with a long lifetime might be overtaken by a later
3298 * certificate with a short lifetime, thus invalidating the
3299 * earlier signature. However, we gotta find a way to leak old
3300 * stuff from the cache, so we do it anyway.
3303 for (xp = cinfo; xp != NULL; xp = xp->link) {
3304 if (strcmp(cp->subject, xp->subject) == 0 &&
3305 strcmp(cp->issuer, xp->issuer) == 0) {
3306 if (ntohl(cp->cert.fstamp) <=
3307 ntohl(xp->cert.fstamp)) {
3323 cp->flags |= CERT_VALID;
3330 * cert_hike - verify the signature using the issuer public key
3334 * XEVNT_CRT bad or missing certificate
3335 * XEVNT_PER host certificate expired
3336 * XEVNT_VFY certificate not verified
3340 struct peer *peer, /* peer structure pointer */
3341 struct cert_info *yp /* issuer certificate */
3344 struct cert_info *xp; /* subject certificate */
3345 X509 *cert; /* X509 certificate */
3349 * Save the issuer on the new certificate, but remember the old
3352 if (peer->issuer != NULL)
3354 peer->issuer = estrdup(yp->issuer);
3359 * If subject Y matches issuer Y, then the certificate trail is
3360 * complete. If Y is not trusted, the server certificate has yet
3361 * been signed, so keep trying. Otherwise, save the group key
3362 * and light the valid bit. If the host certificate is trusted,
3363 * do not execute a sign exchange. If no identity scheme is in
3364 * use, light the identity and proventic bits.
3366 if (strcmp(yp->subject, yp->issuer) == 0) {
3367 if (!(yp->flags & CERT_TRUST))
3371 * If the server has an an identity scheme, fetch the
3372 * identity credentials. If not, the identity is
3373 * verified only by the trusted certificate. The next
3374 * signature will set the server proventic.
3376 peer->crypto |= CRYPTO_FLAG_CERT;
3377 peer->grpkey = yp->grpkey;
3378 if (peer->ident == NULL || !(peer->crypto &
3380 peer->crypto |= CRYPTO_FLAG_VRFY;
3384 * If X exists, verify signature X using public key Y.
3389 ptr = (u_char *)xp->cert.ptr;
3390 cert = d2i_X509(NULL, &ptr, ntohl(xp->cert.vallen));
3392 xp->flags |= CERT_ERROR;
3395 if (X509_verify(cert, yp->pkey) <= 0) {
3397 xp->flags |= CERT_ERROR;
3403 * Signature X is valid only if it begins during the
3406 if ((calcomp(&(xp->first), &(yp->first)) < 0)
3407 || (calcomp(&(xp->first), &(yp->last)) > 0)) {
3408 xp->flags |= CERT_ERROR;
3411 xp->flags |= CERT_SIGN;
3417 * cert_parse - parse x509 certificate and create info/value structures.
3419 * The server certificate includes the version number, issuer name,
3420 * subject name, public key and valid date interval. If the issuer name
3421 * is the same as the subject name, the certificate is self signed and
3422 * valid only if the server is configured as trustable. If the names are
3423 * different, another issuer has signed the server certificate and
3424 * vouched for it. In this case the server certificate is valid if
3425 * verified by the issuer public key.
3427 * Returns certificate info/value pointer if valid, NULL if not.
3429 struct cert_info * /* certificate information structure */
3431 const u_char *asn1cert, /* X509 certificate */
3432 long len, /* certificate length */
3433 tstamp_t fstamp /* filestamp */
3436 X509 *cert; /* X509 certificate */
3437 struct cert_info *ret; /* certificate info/value */
3439 char pathbuf[MAXFILENAME];
3443 struct calendar fscal;
3446 * Decode ASN.1 objects and construct certificate structure.
3449 if ((cert = d2i_X509(NULL, &ptr, len)) == NULL) {
3450 msyslog(LOG_ERR, "cert_parse: %s",
3451 ERR_error_string(ERR_get_error(), NULL));
3456 X509_print_fp(stdout, cert);
3460 * Extract version, subject name and public key.
3462 ret = emalloc_zero(sizeof(*ret));
3463 if ((ret->pkey = X509_get_pubkey(cert)) == NULL) {
3464 msyslog(LOG_ERR, "cert_parse: %s",
3465 ERR_error_string(ERR_get_error(), NULL));
3470 ret->version = X509_get_version(cert);
3471 X509_NAME_oneline(X509_get_subject_name(cert), pathbuf,
3473 pch = strstr(pathbuf, "CN=");
3475 msyslog(LOG_NOTICE, "cert_parse: invalid subject %s",
3481 ret->subject = estrdup(pch + 3);
3484 * Extract remaining objects. Note that the NTP serial number is
3485 * the NTP seconds at the time of signing, but this might not be
3486 * the case for other authority. We don't bother to check the
3487 * objects at this time, since the real crunch can happen only
3488 * when the time is valid but not yet certificated.
3490 ret->nid = X509_get_signature_nid(cert);
3491 ret->digest = (const EVP_MD *)EVP_get_digestbynid(ret->nid);
3493 (u_long)ASN1_INTEGER_get(X509_get_serialNumber(cert));
3494 X509_NAME_oneline(X509_get_issuer_name(cert), pathbuf,
3496 if ((pch = strstr(pathbuf, "CN=")) == NULL) {
3497 msyslog(LOG_NOTICE, "cert_parse: invalid issuer %s",
3503 ret->issuer = estrdup(pch + 3);
3504 asn_to_calendar(X509_get0_notBefore(cert), &(ret->first));
3505 asn_to_calendar(X509_get0_notAfter(cert), &(ret->last));
3508 * Extract extension fields. These are ad hoc ripoffs of
3509 * currently assigned functions and will certainly be changed
3510 * before prime time.
3512 cnt = X509_get_ext_count(cert);
3513 for (i = 0; i < cnt; i++) {
3514 X509_EXTENSION *ext;
3517 ASN1_OCTET_STRING *data;
3519 ext = X509_get_ext(cert, i);
3520 obj = X509_EXTENSION_get_object(ext);
3521 nid = OBJ_obj2nid(obj);
3526 * If a key_usage field is present, we decode whether
3527 * this is a trusted or private certificate. This is
3528 * dorky; all we want is to compare NIDs, but OpenSSL
3529 * insists on BIO text strings.
3531 case NID_ext_key_usage:
3532 bp = BIO_new(BIO_s_mem());
3533 X509V3_EXT_print(bp, ext, 0, 0);
3534 BIO_gets(bp, pathbuf, sizeof(pathbuf));
3536 if (strcmp(pathbuf, "Trust Root") == 0)
3537 ret->flags |= CERT_TRUST;
3538 else if (strcmp(pathbuf, "Private") == 0)
3539 ret->flags |= CERT_PRIV;
3540 DPRINTF(1, ("cert_parse: %s: %s\n",
3541 OBJ_nid2ln(nid), pathbuf));
3545 * If a NID_subject_key_identifier field is present, it
3546 * contains the GQ public key.
3548 case NID_subject_key_identifier:
3549 data = X509_EXTENSION_get_data(ext);
3550 ret->grpkey = BN_bin2bn(&data->data[2],
3551 data->length - 2, NULL);
3554 DPRINTF(1, ("cert_parse: %s\n",
3559 if (strcmp(ret->subject, ret->issuer) == 0) {
3562 * If certificate is self signed, verify signature.
3564 if (X509_verify(cert, ret->pkey) <= 0) {
3566 "cert_parse: signature not verified %s",
3575 * Check for a certificate loop.
3577 if (strcmp((const char *)hostval.ptr, ret->issuer) == 0) {
3579 "cert_parse: certificate trail loop %s",
3588 * Verify certificate valid times. Note that certificates cannot
3591 (void)ntpcal_ntp_to_date(&fscal, fstamp, NULL);
3592 if ((calcomp(&(ret->first), &(ret->last)) > 0)
3593 || (calcomp(&(ret->first), &fscal) < 0)) {
3595 "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",
3597 ret->first.year, ret->first.month, ret->first.monthday,
3598 ret->first.hour, ret->first.minute, ret->first.second,
3599 ret->last.year, ret->last.month, ret->last.monthday,
3600 ret->last.hour, ret->last.minute, ret->last.second,
3601 fscal.year, fscal.month, fscal.monthday,
3602 fscal.hour, fscal.minute, fscal.second);
3609 * Build the value structure to sign and send later.
3611 ret->cert.fstamp = htonl(fstamp);
3612 ret->cert.vallen = htonl(len);
3613 ret->cert.ptr = emalloc(len);
3614 memcpy(ret->cert.ptr, asn1cert, len);
3621 * cert_free - free certificate information structure
3625 struct cert_info *cinf /* certificate info/value structure */
3628 if (cinf->pkey != NULL)
3629 EVP_PKEY_free(cinf->pkey);
3630 if (cinf->subject != NULL)
3631 free(cinf->subject);
3632 if (cinf->issuer != NULL)
3634 if (cinf->grpkey != NULL)
3635 BN_free(cinf->grpkey);
3636 value_free(&cinf->cert);
3642 * crypto_key - load cryptographic parameters and keys
3644 * This routine searches the key cache for matching name in the form
3645 * ntpkey_<key>_<name>, where <key> is one of host, sign, iff, gq, mv,
3646 * and <name> is the host/group name. If not found, it tries to load a
3647 * PEM-encoded file of the same name and extracts the filestamp from
3648 * the first line of the file name. It returns the key pointer if valid,
3651 static struct pkey_info *
3653 char *cp, /* file name */
3654 char *passwd1, /* password */
3655 sockaddr_u *addr /* IP address */
3658 FILE *str; /* file handle */
3659 struct pkey_info *pkp; /* generic key */
3660 EVP_PKEY *pkey = NULL; /* public/private key */
3662 char filename[MAXFILENAME]; /* name of key file */
3663 char linkname[MAXFILENAME]; /* filestamp buffer) */
3664 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3668 * Search the key cache for matching key and name.
3670 for (pkp = pkinfo; pkp != NULL; pkp = pkp->link) {
3671 if (strcmp(cp, pkp->name) == 0)
3676 * Open the key file. If the first character of the file name is
3677 * not '/', prepend the keys directory string. If something goes
3678 * wrong, abandon ship.
3681 strlcpy(filename, cp, sizeof(filename));
3683 snprintf(filename, sizeof(filename), "%s/%s", keysdir,
3685 str = fopen(filename, "r");
3690 * Read the filestamp, which is contained in the first line.
3692 if ((ptr = fgets(linkname, sizeof(linkname), str)) == NULL) {
3693 msyslog(LOG_ERR, "crypto_key: empty file %s",
3698 if ((ptr = strrchr(ptr, '.')) == NULL) {
3699 msyslog(LOG_ERR, "crypto_key: no filestamp %s",
3704 if (sscanf(++ptr, "%u", &fstamp) != 1) {
3705 msyslog(LOG_ERR, "crypto_key: invalid filestamp %s",
3712 * Read and decrypt PEM-encoded private key. If it fails to
3713 * decrypt, game over.
3715 pkey = PEM_read_PrivateKey(str, NULL, NULL, passwd1);
3718 msyslog(LOG_ERR, "crypto_key: %s",
3719 ERR_error_string(ERR_get_error(), NULL));
3724 * Make a new entry in the key cache.
3726 pkp = emalloc(sizeof(struct pkey_info));
3730 pkp->name = estrdup(cp);
3731 pkp->fstamp = fstamp;
3734 * Leave tracks in the cryptostats.
3736 if ((ptr = strrchr(linkname, '\n')) != NULL)
3738 snprintf(statstr, sizeof(statstr), "%s mod %d", &linkname[2],
3739 EVP_PKEY_size(pkey) * 8);
3740 record_crypto_stats(addr, statstr);
3742 DPRINTF(1, ("crypto_key: %s\n", statstr));
3745 if (EVP_PKEY_base_id(pkey) == EVP_PKEY_DSA)
3746 DSA_print_fp(stdout, EVP_PKEY_get0_DSA(pkey), 0);
3747 else if (EVP_PKEY_base_id(pkey) == EVP_PKEY_RSA)
3748 RSA_print_fp(stdout, EVP_PKEY_get0_RSA(pkey), 0);
3756 ***********************************************************************
3758 * The following routines are used only at initialization time *
3760 ***********************************************************************
3763 * crypto_cert - load certificate from file
3765 * This routine loads an X.509 RSA or DSA certificate from a file and
3766 * constructs a info/cert value structure for this machine. The
3767 * structure includes a filestamp extracted from the file name. Later
3768 * the certificate can be sent to another machine on request.
3770 * Returns certificate info/value pointer if valid, NULL if not.
3772 static struct cert_info * /* certificate information */
3774 char *cp /* file name */
3777 struct cert_info *ret; /* certificate information */
3778 FILE *str; /* file handle */
3779 char filename[MAXFILENAME]; /* name of certificate file */
3780 char linkname[MAXFILENAME]; /* filestamp buffer */
3781 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3782 tstamp_t fstamp; /* filestamp */
3785 char *name, *header;
3789 * Open the certificate file. If the first character of the file
3790 * name is not '/', prepend the keys directory string. If
3791 * something goes wrong, abandon ship.
3794 strlcpy(filename, cp, sizeof(filename));
3796 snprintf(filename, sizeof(filename), "%s/%s", keysdir,
3798 str = fopen(filename, "r");
3803 * Read the filestamp, which is contained in the first line.
3805 if ((ptr = fgets(linkname, sizeof(linkname), str)) == NULL) {
3806 msyslog(LOG_ERR, "crypto_cert: empty file %s",
3811 if ((ptr = strrchr(ptr, '.')) == NULL) {
3812 msyslog(LOG_ERR, "crypto_cert: no filestamp %s",
3817 if (sscanf(++ptr, "%u", &fstamp) != 1) {
3818 msyslog(LOG_ERR, "crypto_cert: invalid filestamp %s",
3825 * Read PEM-encoded certificate and install.
3827 if (!PEM_read(str, &name, &header, &data, &len)) {
3828 msyslog(LOG_ERR, "crypto_cert: %s",
3829 ERR_error_string(ERR_get_error(), NULL));
3835 if (strcmp(name, "CERTIFICATE") != 0) {
3836 msyslog(LOG_NOTICE, "crypto_cert: wrong PEM type %s",
3845 * Parse certificate and generate info/value structure. The
3846 * pointer and copy nonsense is due something broken in Solaris.
3848 ret = cert_parse(data, len, fstamp);
3853 if ((ptr = strrchr(linkname, '\n')) != NULL)
3855 snprintf(statstr, sizeof(statstr), "%s 0x%x len %lu",
3856 &linkname[2], ret->flags, len);
3857 record_crypto_stats(NULL, statstr);
3858 DPRINTF(1, ("crypto_cert: %s\n", statstr));
3864 * crypto_setup - load keys, certificate and identity parameters
3866 * This routine loads the public/private host key and certificate. If
3867 * available, it loads the public/private sign key, which defaults to
3868 * the host key. The host key must be RSA, but the sign key can be
3869 * either RSA or DSA. If a trusted certificate, it loads the identity
3870 * parameters. In either case, the public key on the certificate must
3871 * agree with the sign key.
3873 * Required but missing files and inconsistent data and errors are
3874 * fatal. Allowing configuration to continue would be hazardous and
3875 * require really messy error checks.
3880 struct pkey_info *pinfo; /* private/public key */
3881 char filename[MAXFILENAME]; /* file name buffer */
3882 char hostname[MAXFILENAME]; /* host name buffer */
3884 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3885 l_fp seed; /* crypto PRNG seed as NTP timestamp */
3891 * Check for correct OpenSSL version and avoid initialization in
3892 * the case of multiple crypto commands.
3894 if (crypto_flags & CRYPTO_FLAG_ENAB) {
3896 "crypto_setup: spurious crypto command");
3899 ssl_check_version();
3902 * Load required random seed file and seed the random number
3903 * generator. Be default, it is found as .rnd in the user home
3904 * directory. The root home directory may be / or /root,
3905 * depending on the system. Wiggle the contents a bit and write
3906 * it back so the sequence does not repeat when we next restart.
3908 if (!RAND_status()) {
3909 if (rand_file == NULL) {
3910 RAND_file_name(filename, sizeof(filename));
3911 randfile = filename;
3912 } else if (*rand_file != '/') {
3913 snprintf(filename, sizeof(filename), "%s/%s",
3914 keysdir, rand_file);
3915 randfile = filename;
3917 randfile = rand_file;
3919 if ((bytes = RAND_load_file(randfile, -1)) == 0) {
3921 "crypto_setup: random seed file %s missing",
3925 arc4random_buf(&seed, sizeof(l_fp));
3926 RAND_seed(&seed, sizeof(l_fp));
3927 RAND_write_file(randfile);
3928 DPRINTF(1, ("crypto_setup: OpenSSL version %lx random seed file %s bytes read %d\n",
3929 OpenSSL_version_num(), randfile, bytes));
3934 * Initialize structures.
3936 gethostname(hostname, sizeof(hostname));
3937 if (host_filename != NULL)
3938 strlcpy(hostname, host_filename, sizeof(hostname));
3940 passwd = estrdup(hostname);
3941 memset(&hostval, 0, sizeof(hostval));
3942 memset(&pubkey, 0, sizeof(pubkey));
3943 memset(&tai_leap, 0, sizeof(tai_leap));
3946 * Load required host key from file "ntpkey_host_<hostname>". If
3947 * no host key file is not found or has invalid password, life
3948 * as we know it ends. The host key also becomes the default
3951 snprintf(filename, sizeof(filename), "ntpkey_host_%s", hostname);
3952 pinfo = crypto_key(filename, passwd, NULL);
3953 if (pinfo == NULL) {
3955 "crypto_setup: host key file %s not found or corrupt",
3959 if (EVP_PKEY_base_id(pinfo->pkey) != EVP_PKEY_RSA) {
3961 "crypto_setup: host key is not RSA key type");
3964 host_pkey = pinfo->pkey;
3965 sign_pkey = host_pkey;
3966 hostval.fstamp = htonl(pinfo->fstamp);
3969 * Construct public key extension field for agreement scheme.
3971 len = i2d_PublicKey(host_pkey, NULL);
3974 i2d_PublicKey(host_pkey, &ptr);
3975 pubkey.fstamp = hostval.fstamp;
3976 pubkey.vallen = htonl(len);
3979 * Load optional sign key from file "ntpkey_sign_<hostname>". If
3980 * available, it becomes the sign key.
3982 snprintf(filename, sizeof(filename), "ntpkey_sign_%s", hostname);
3983 pinfo = crypto_key(filename, passwd, NULL);
3985 sign_pkey = pinfo->pkey;
3988 * Load required certificate from file "ntpkey_cert_<hostname>".
3990 snprintf(filename, sizeof(filename), "ntpkey_cert_%s", hostname);
3991 cinfo = crypto_cert(filename);
3992 if (cinfo == NULL) {
3994 "crypto_setup: certificate file %s not found or corrupt",
3999 sign_digest = cinfo->digest;
4000 sign_siglen = EVP_PKEY_size(sign_pkey);
4001 if (cinfo->flags & CERT_PRIV)
4002 crypto_flags |= CRYPTO_FLAG_PRIV;
4005 * The certificate must be self-signed.
4007 if (strcmp(cinfo->subject, cinfo->issuer) != 0) {
4009 "crypto_setup: certificate %s is not self-signed",
4013 hostval.ptr = estrdup(cinfo->subject);
4014 hostval.vallen = htonl(strlen(cinfo->subject));
4015 sys_hostname = hostval.ptr;
4016 ptr = (u_char *)strchr(sys_hostname, '@');
4018 sys_groupname = estrdup((char *)++ptr);
4019 if (ident_filename != NULL)
4020 strlcpy(hostname, ident_filename, sizeof(hostname));
4023 * Load optional IFF parameters from file
4024 * "ntpkey_iffkey_<hostname>".
4026 snprintf(filename, sizeof(filename), "ntpkey_iffkey_%s",
4028 iffkey_info = crypto_key(filename, passwd, NULL);
4029 if (iffkey_info != NULL)
4030 crypto_flags |= CRYPTO_FLAG_IFF;
4033 * Load optional GQ parameters from file
4034 * "ntpkey_gqkey_<hostname>".
4036 snprintf(filename, sizeof(filename), "ntpkey_gqkey_%s",
4038 gqkey_info = crypto_key(filename, passwd, NULL);
4039 if (gqkey_info != NULL)
4040 crypto_flags |= CRYPTO_FLAG_GQ;
4043 * Load optional MV parameters from file
4044 * "ntpkey_mvkey_<hostname>".
4046 snprintf(filename, sizeof(filename), "ntpkey_mvkey_%s",
4048 mvkey_info = crypto_key(filename, passwd, NULL);
4049 if (mvkey_info != NULL)
4050 crypto_flags |= CRYPTO_FLAG_MV;
4053 * We met the enemy and he is us. Now strike up the dance.
4055 crypto_flags |= CRYPTO_FLAG_ENAB | (cinfo->nid << 16);
4056 snprintf(statstr, sizeof(statstr), "setup 0x%x host %s %s",
4057 crypto_flags, hostname, OBJ_nid2ln(cinfo->nid));
4058 record_crypto_stats(NULL, statstr);
4059 DPRINTF(1, ("crypto_setup: %s\n", statstr));
4064 * crypto_config - configure data from the crypto command.
4068 int item, /* configuration item */
4069 char *cp /* item name */
4074 DPRINTF(1, ("crypto_config: item %d %s\n", item, cp));
4079 * Set host name (host).
4081 case CRYPTO_CONF_PRIV:
4082 if (NULL != host_filename)
4083 free(host_filename);
4084 host_filename = estrdup(cp);
4088 * Set group name (ident).
4090 case CRYPTO_CONF_IDENT:
4091 if (NULL != ident_filename)
4092 free(ident_filename);
4093 ident_filename = estrdup(cp);
4097 * Set private key password (pw).
4099 case CRYPTO_CONF_PW:
4102 passwd = estrdup(cp);
4106 * Set random seed file name (randfile).
4108 case CRYPTO_CONF_RAND:
4109 if (NULL != rand_file)
4111 rand_file = estrdup(cp);
4115 * Set message digest NID.
4117 case CRYPTO_CONF_NID:
4118 nid = OBJ_sn2nid(cp);
4121 "crypto_config: invalid digest name %s", cp);
4129 * Get the payload size (internal value length) of an extension packet.
4130 * If the inner value size does not match the outer packet size (that
4131 * is, the value would end behind the frame given by the opcode/size
4132 * field) the function will effectively return UINT_MAX. If the frame is
4133 * too short to hold a variable-sized value, the return value is zero.
4137 const struct exten * ep)
4139 typedef const u_char *BPTR;
4147 head_size = (BPTR)(&ep->vallen + 1) - (BPTR)ep;
4148 extn_size = (uint16_t)(ntohl(ep->opcode) & 0x0000ffff);
4149 if (extn_size >= head_size) {
4150 data_size = (uint32_t)ntohl(ep->vallen);
4151 if (data_size > extn_size - head_size)
4152 data_size = ~(size_t)0u;
4155 return (u_int)data_size;
4157 # else /* !AUTOKEY follows */
4158 int ntp_crypto_bs_pubkey;
4159 # endif /* !AUTOKEY */