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 # if defined(OPENSSL) && defined(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW)
272 /* [Bug 3457] set flags and don't kill them again */
273 EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
274 EVP_DigestInit_ex(ctx, EVP_get_digestbynid(crypto_nid), NULL);
276 EVP_DigestInit(ctx, EVP_get_digestbynid(crypto_nid));
278 EVP_DigestUpdate(ctx, (u_char *)header, hdlen);
279 EVP_DigestFinal(ctx, dgst, &len);
280 EVP_MD_CTX_free(ctx);
281 memcpy(&keyid, dgst, 4);
282 keyid = ntohl(keyid);
284 MD5auth_setkey(keyno, crypto_nid, dgst, len, NULL);
285 authtrust(keyno, lifetime);
287 DPRINTF(2, ("session_key: %s > %s %08x %08x hash %08x life %lu\n",
288 stoa(srcadr), stoa(dstadr), keyno,
289 private, keyid, lifetime));
296 * make_keylist - generate key list
300 * XEVNT_ERR protocol error
302 * This routine constructs a pseudo-random sequence by repeatedly
303 * hashing the session key starting from a given source address,
304 * destination address, private value and the next key ID of the
305 * preceeding session key. The last entry on the list is saved along
306 * with its sequence number and public signature.
310 struct peer *peer, /* peer structure pointer */
311 struct interface *dstadr /* interface */
314 EVP_MD_CTX *ctx; /* signature context */
315 tstamp_t tstamp; /* NTP timestamp */
316 struct autokey *ap; /* autokey pointer */
317 struct value *vp; /* value pointer */
318 keyid_t keyid = 0; /* next key ID */
319 keyid_t cookie; /* private value */
328 * Allocate the key list if necessary.
330 tstamp = crypto_time();
331 if (peer->keylist == NULL)
332 peer->keylist = eallocarray(NTP_MAXSESSION,
336 * Generate an initial key ID which is unique and greater than
340 keyid = ntp_random() & 0xffffffff;
341 if (keyid <= NTP_MAXKEY)
344 if (authhavekey(keyid))
350 * Generate up to NTP_MAXSESSION session keys. Stop if the
351 * next one would not be unique or not a session key ID or if
352 * it would expire before the next poll. The private value
353 * included in the hash is zero if broadcast mode, the peer
354 * cookie if client mode or the host cookie if symmetric modes.
356 mpoll = 1U << min(peer->ppoll, peer->hpoll);
357 lifetime = min((1UL << sys_automax), NTP_MAXSESSION * mpoll);
358 if (peer->hmode == MODE_BROADCAST)
361 cookie = peer->pcookie;
362 for (i = 0; i < NTP_MAXSESSION; i++) {
363 peer->keylist[i] = keyid;
365 keyid = session_key(&dstadr->sin, &peer->srcadr, keyid,
366 cookie, lifetime + mpoll);
368 if (auth_havekey(keyid) || keyid <= NTP_MAXKEY ||
369 lifetime < 0 || tstamp == 0)
374 * Save the last session key ID, sequence number and timestamp,
375 * then sign these values for later retrieval by the clients. Be
376 * careful not to use invalid key media. Use the public values
377 * timestamp as filestamp.
381 vp->ptr = emalloc(sizeof(struct autokey));
382 ap = (struct autokey *)vp->ptr;
383 ap->seq = htonl(peer->keynumber);
384 ap->key = htonl(keyid);
385 vp->tstamp = htonl(tstamp);
386 vp->fstamp = hostval.tstamp;
387 vp->vallen = htonl(sizeof(struct autokey));
391 vp->sig = emalloc(sign_siglen);
392 ctx = EVP_MD_CTX_new();
393 EVP_SignInit(ctx, sign_digest);
394 EVP_SignUpdate(ctx, (u_char *)vp, 12);
395 EVP_SignUpdate(ctx, vp->ptr, sizeof(struct autokey));
396 if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
397 INSIST(len <= sign_siglen);
398 vp->siglen = htonl(len);
399 peer->flags |= FLAG_ASSOC;
401 EVP_MD_CTX_free(ctx);
403 DPRINTF(1, ("make_keys: %d %08x %08x ts %u fs %u poll %d\n",
404 peer->keynumber, keyid, cookie, ntohl(vp->tstamp),
405 ntohl(vp->fstamp), peer->hpoll));
411 * crypto_recv - parse extension fields
413 * This routine is called when the packet has been matched to an
414 * association and passed sanity, format and MAC checks. We believe the
415 * extension field values only if the field has proper format and
416 * length, the timestamp and filestamp are valid and the signature has
417 * valid length and is verified. There are a few cases where some values
418 * are believed even if the signature fails, but only if the proventic
423 * XEVNT_ERR protocol error
424 * XEVNT_LEN bad field format or length
428 struct peer *peer, /* peer structure pointer */
429 struct recvbuf *rbufp /* packet buffer pointer */
432 const EVP_MD *dp; /* message digest algorithm */
433 u_int32 *pkt; /* receive packet pointer */
434 struct autokey *ap, *bp; /* autokey pointer */
435 struct exten *ep, *fp; /* extension pointers */
436 struct cert_info *xinfo; /* certificate info pointer */
437 int macbytes; /* length of MAC field, signed by intention */
438 int authlen; /* offset of MAC field */
439 associd_t associd; /* association ID */
440 tstamp_t fstamp = 0; /* filestamp */
441 u_int len; /* extension field length */
442 u_int code; /* extension field opcode */
443 u_int vallen = 0; /* value length */
444 X509 *cert; /* X509 certificate */
445 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
446 keyid_t cookie; /* crumbles */
447 int hismode; /* packet mode */
453 * Initialize. Note that the packet has already been checked for
454 * valid format and extension field lengths. First extract the
455 * field length, command code and association ID in host byte
456 * order. These are used with all commands and modes. Then check
457 * the version number, which must be 2, and length, which must
458 * be at least 8 for requests and VALUE_LEN (24) for responses.
459 * Packets that fail either test sink without a trace. The
460 * association ID is saved only if nonzero.
462 authlen = LEN_PKT_NOMAC;
463 hismode = (int)PKT_MODE((&rbufp->recv_pkt)->li_vn_mode);
464 while ((macbytes = rbufp->recv_length - authlen) > (int)MAX_MAC_LEN) {
465 /* We can be reasonably sure that we can read at least
466 * the opcode and the size field here. More stringent
467 * checks follow up shortly.
469 pkt = (u_int32 *)&rbufp->recv_pkt + authlen / 4;
470 ep = (struct exten *)pkt;
471 code = ntohl(ep->opcode) & 0xffff0000;
472 len = ntohl(ep->opcode) & 0x0000ffff;
473 // HMS: Why pkt[1] instead of ep->associd ?
474 associd = (associd_t)ntohl(pkt[1]);
476 DPRINTF(1, ("crypto_recv: flags 0x%x ext offset %d len %u code 0x%x associd %d\n",
477 peer->crypto, authlen, len, code >> 16,
481 * Check version number and field length. If bad,
482 * quietly ignore the packet.
484 if (((code >> 24) & 0x3f) != CRYPTO_VN || len < 8) {
486 code |= CRYPTO_ERROR;
489 /* Check if the declared size fits into the remaining
490 * buffer. We *know* 'macbytes' > 0 here!
492 if (len > (u_int)macbytes) {
493 DPRINTF(1, ("crypto_recv: possible attack detected, associd %d\n",
498 /* Check if the paylod of the extension fits into the
501 if (len >= VALUE_LEN) {
502 fstamp = ntohl(ep->fstamp);
503 vallen = ntohl(ep->vallen);
505 * Bug 2761: I hope this isn't too early...
508 || len - VALUE_LEN < vallen)
514 * Install status word, host name, signature scheme and
515 * association ID. In OpenSSL the signature algorithm is
516 * bound to the digest algorithm, so the NID completely
517 * defines the signature scheme. Note the request and
518 * response are identical, but neither is validated by
519 * signature. The request is processed here only in
520 * symmetric modes. The server name field might be
521 * useful to implement access controls in future.
526 * If our state machine is running when this
527 * message arrives, the other fellow might have
528 * restarted. However, this could be an
529 * intruder, so just clamp the poll interval and
530 * find out for ourselves. Otherwise, pass the
531 * extension field to the transmit side.
533 if (peer->crypto & CRYPTO_FLAG_CERT) {
538 if (peer->assoc != associd) {
542 free(peer->cmmd); /* will be set again! */
546 fp->associd = htonl(peer->associd);
550 case CRYPTO_ASSOC | CRYPTO_RESP:
553 * Discard the message if it has already been
554 * stored or the message has been amputated.
557 if (peer->assoc != associd)
561 INSIST(len >= VALUE_LEN);
562 if (vallen == 0 || vallen > MAXHOSTNAME ||
563 len - VALUE_LEN < vallen) {
567 DPRINTF(1, ("crypto_recv: ident host 0x%x %d server 0x%x %d\n",
568 crypto_flags, peer->associd, fstamp,
570 temp32 = crypto_flags & CRYPTO_FLAG_MASK;
573 * If the client scheme is PC, the server scheme
574 * must be PC. The public key and identity are
575 * presumed valid, so we skip the certificate
576 * and identity exchanges and move immediately
577 * to the cookie exchange which confirms the
580 if (crypto_flags & CRYPTO_FLAG_PRIV) {
581 if (!(fstamp & CRYPTO_FLAG_PRIV)) {
585 fstamp |= CRYPTO_FLAG_CERT |
586 CRYPTO_FLAG_VRFY | CRYPTO_FLAG_SIGN;
589 * It is an error if either peer supports
590 * identity, but the other does not.
592 } else if (hismode == MODE_ACTIVE || hismode ==
594 if ((temp32 && !(fstamp &
595 CRYPTO_FLAG_MASK)) ||
596 (!temp32 && (fstamp &
597 CRYPTO_FLAG_MASK))) {
604 * Discard the message if the signature digest
605 * NID is not supported.
607 temp32 = (fstamp >> 16) & 0xffff;
609 (const EVP_MD *)EVP_get_digestbynid(temp32);
616 * Save status word, host name and message
617 * digest/signature type. If this is from a
618 * broadcast and the association ID has changed,
619 * request the autokey values.
621 peer->assoc = associd;
622 if (hismode == MODE_SERVER)
623 fstamp |= CRYPTO_FLAG_AUTO;
624 if (!(fstamp & CRYPTO_FLAG_TAI))
625 fstamp |= CRYPTO_FLAG_LEAP;
626 RAND_bytes((u_char *)&peer->hcookie, 4);
627 peer->crypto = fstamp;
629 if (peer->subject != NULL)
631 peer->subject = emalloc(vallen + 1);
632 memcpy(peer->subject, ep->pkt, vallen);
633 peer->subject[vallen] = '\0';
634 if (peer->issuer != NULL)
636 peer->issuer = estrdup(peer->subject);
637 snprintf(statstr, sizeof(statstr),
638 "assoc %d %d host %s %s", peer->associd,
639 peer->assoc, peer->subject,
641 record_crypto_stats(&peer->srcadr, statstr);
642 DPRINTF(1, ("crypto_recv: %s\n", statstr));
646 * Decode X509 certificate in ASN.1 format and extract
647 * the data containing, among other things, subject
648 * name and public key. In the default identification
649 * scheme, the certificate trail is followed to a self
650 * signed trusted certificate.
652 case CRYPTO_CERT | CRYPTO_RESP:
655 * Discard the message if empty or invalid.
660 if ((rval = crypto_verify(ep, NULL, peer)) !=
665 * Scan the certificate list to delete old
666 * versions and link the newest version first on
667 * the list. Then, verify the signature. If the
668 * certificate is bad or missing, just ignore
671 if ((xinfo = cert_install(ep, peer)) == NULL) {
675 if ((rval = cert_hike(peer, xinfo)) != XEVNT_OK)
679 * We plug in the public key and lifetime from
680 * the first certificate received. However, note
681 * that this certificate might not be signed by
682 * the server, so we can't check the
683 * signature/digest NID.
685 if (peer->pkey == NULL) {
686 puch = xinfo->cert.ptr;
687 cert = d2i_X509(NULL, &puch,
688 ntohl(xinfo->cert.vallen));
689 peer->pkey = X509_get_pubkey(cert);
692 peer->flash &= ~TEST8;
694 snprintf(statstr, sizeof(statstr),
695 "cert %s %s 0x%x %s (%u) fs %u",
696 xinfo->subject, xinfo->issuer, xinfo->flags,
697 OBJ_nid2ln(temp32), temp32,
699 record_crypto_stats(&peer->srcadr, statstr);
700 DPRINTF(1, ("crypto_recv: %s\n", statstr));
704 * Schnorr (IFF) identity scheme. This scheme is
705 * designed for use with shared secret server group keys
706 * and where the certificate may be generated by a third
707 * party. The client sends a challenge to the server,
708 * which performs a calculation and returns the result.
709 * A positive result is possible only if both client and
710 * server contain the same secret group key.
712 case CRYPTO_IFF | CRYPTO_RESP:
715 * Discard the message if invalid.
717 if ((rval = crypto_verify(ep, NULL, peer)) !=
722 * If the challenge matches the response, the
723 * server public key, signature and identity are
724 * all verified at the same time. The server is
725 * declared trusted, so we skip further
726 * certificate exchanges and move immediately to
727 * the cookie exchange.
729 if ((rval = crypto_iff(ep, peer)) != XEVNT_OK)
732 peer->crypto |= CRYPTO_FLAG_VRFY;
733 peer->flash &= ~TEST8;
734 snprintf(statstr, sizeof(statstr), "iff %s fs %u",
735 peer->issuer, ntohl(ep->fstamp));
736 record_crypto_stats(&peer->srcadr, statstr);
737 DPRINTF(1, ("crypto_recv: %s\n", statstr));
741 * Guillou-Quisquater (GQ) identity scheme. This scheme
742 * is designed for use with public certificates carrying
743 * the GQ public key in an extension field. The client
744 * sends a challenge to the server, which performs a
745 * calculation and returns the result. A positive result
746 * is possible only if both client and server contain
747 * the same group key and the server has the matching GQ
750 case CRYPTO_GQ | CRYPTO_RESP:
753 * Discard the message if invalid
755 if ((rval = crypto_verify(ep, NULL, peer)) !=
760 * If the challenge matches the response, the
761 * server public key, signature and identity are
762 * all verified at the same time. The server is
763 * declared trusted, so we skip further
764 * certificate exchanges and move immediately to
765 * the cookie exchange.
767 if ((rval = crypto_gq(ep, peer)) != XEVNT_OK)
770 peer->crypto |= CRYPTO_FLAG_VRFY;
771 peer->flash &= ~TEST8;
772 snprintf(statstr, sizeof(statstr), "gq %s fs %u",
773 peer->issuer, ntohl(ep->fstamp));
774 record_crypto_stats(&peer->srcadr, statstr);
775 DPRINTF(1, ("crypto_recv: %s\n", statstr));
779 * Mu-Varadharajan (MV) identity scheme. This scheme is
780 * designed for use with three levels of trust, trusted
781 * host, server and client. The trusted host key is
782 * opaque to servers and clients; the server keys are
783 * opaque to clients and each client key is different.
784 * Client keys can be revoked without requiring new key
787 case CRYPTO_MV | CRYPTO_RESP:
790 * Discard the message if invalid.
792 if ((rval = crypto_verify(ep, NULL, peer)) !=
797 * If the challenge matches the response, the
798 * server public key, signature and identity are
799 * all verified at the same time. The server is
800 * declared trusted, so we skip further
801 * certificate exchanges and move immediately to
802 * the cookie exchange.
804 if ((rval = crypto_mv(ep, peer)) != XEVNT_OK)
807 peer->crypto |= CRYPTO_FLAG_VRFY;
808 peer->flash &= ~TEST8;
809 snprintf(statstr, sizeof(statstr), "mv %s fs %u",
810 peer->issuer, ntohl(ep->fstamp));
811 record_crypto_stats(&peer->srcadr, statstr);
812 DPRINTF(1, ("crypto_recv: %s\n", statstr));
817 * Cookie response in client and symmetric modes. If the
818 * cookie bit is set, the working cookie is the EXOR of
819 * the current and new values.
821 case CRYPTO_COOK | CRYPTO_RESP:
824 * Discard the message if invalid or signature
825 * not verified with respect to the cookie
828 if ((rval = crypto_verify(ep, &peer->cookval,
833 * Decrypt the cookie, hunting all the time for
836 if (vallen == (u_int)EVP_PKEY_size(host_pkey)) {
837 RSA *rsa = EVP_PKEY_get0_RSA(host_pkey);
838 u_int32 *cookiebuf = malloc(RSA_size(rsa));
844 if (RSA_private_decrypt(vallen,
848 RSA_PKCS1_OAEP_PADDING) != 4) {
853 cookie = ntohl(*cookiebuf);
862 * Install cookie values and light the cookie
863 * bit. If this is not broadcast client mode, we
867 if (hismode == MODE_ACTIVE || hismode ==
869 peer->pcookie = peer->hcookie ^ cookie;
871 peer->pcookie = cookie;
872 peer->crypto |= CRYPTO_FLAG_COOK;
873 peer->flash &= ~TEST8;
874 snprintf(statstr, sizeof(statstr),
875 "cook %x ts %u fs %u", peer->pcookie,
876 ntohl(ep->tstamp), ntohl(ep->fstamp));
877 record_crypto_stats(&peer->srcadr, statstr);
878 DPRINTF(1, ("crypto_recv: %s\n", statstr));
882 * Install autokey values in broadcast client and
883 * symmetric modes. We have to do this every time the
884 * sever/peer cookie changes or a new keylist is
885 * rolled. Ordinarily, this is automatic as this message
886 * is piggybacked on the first NTP packet sent upon
887 * either of these events. Note that a broadcast client
888 * or symmetric peer can receive this response without a
891 case CRYPTO_AUTO | CRYPTO_RESP:
894 * Discard the message if invalid or signature
895 * not verified with respect to the receive
898 if ((rval = crypto_verify(ep, &peer->recval,
903 * Discard the message if a broadcast client and
904 * the association ID does not match. This might
905 * happen if a broacast server restarts the
906 * protocol. A protocol restart will occur at
907 * the next ASSOC message.
909 if ((peer->cast_flags & MDF_BCLNT) &&
910 peer->assoc != associd)
914 * Install autokey values and light the
915 * autokey bit. This is not hard.
920 if (peer->recval.ptr == NULL)
922 emalloc(sizeof(struct autokey));
923 bp = (struct autokey *)peer->recval.ptr;
924 peer->recval.tstamp = ep->tstamp;
925 peer->recval.fstamp = ep->fstamp;
926 ap = (struct autokey *)ep->pkt;
927 bp->seq = ntohl(ap->seq);
928 bp->key = ntohl(ap->key);
929 peer->pkeyid = bp->key;
930 peer->crypto |= CRYPTO_FLAG_AUTO;
931 peer->flash &= ~TEST8;
932 snprintf(statstr, sizeof(statstr),
933 "auto seq %d key %x ts %u fs %u", bp->seq,
934 bp->key, ntohl(ep->tstamp),
936 record_crypto_stats(&peer->srcadr, statstr);
937 DPRINTF(1, ("crypto_recv: %s\n", statstr));
941 * X509 certificate sign response. Validate the
942 * certificate signed by the server and install. Later
943 * this can be provided to clients of this server in
944 * lieu of the self signed certificate in order to
945 * validate the public key.
947 case CRYPTO_SIGN | CRYPTO_RESP:
950 * Discard the message if invalid.
952 if ((rval = crypto_verify(ep, NULL, peer)) !=
957 * Scan the certificate list to delete old
958 * versions and link the newest version first on
961 if ((xinfo = cert_install(ep, peer)) == NULL) {
965 peer->crypto |= CRYPTO_FLAG_SIGN;
966 peer->flash &= ~TEST8;
968 snprintf(statstr, sizeof(statstr),
969 "sign %s %s 0x%x %s (%u) fs %u",
970 xinfo->subject, xinfo->issuer, xinfo->flags,
971 OBJ_nid2ln(temp32), temp32,
973 record_crypto_stats(&peer->srcadr, statstr);
974 DPRINTF(1, ("crypto_recv: %s\n", statstr));
978 * Install leapseconds values. While the leapsecond
979 * values epoch, TAI offset and values expiration epoch
980 * are retained, only the current TAI offset is provided
981 * via the kernel to other applications.
983 case CRYPTO_LEAP | CRYPTO_RESP:
985 * Discard the message if invalid. We can't
986 * compare the value timestamps here, as they
987 * can be updated by different servers.
989 rval = crypto_verify(ep, NULL, peer);
990 if ((rval != XEVNT_OK ) ||
991 (vallen != 3*sizeof(uint32_t)) )
994 /* Check if we can update the basic TAI offset
995 * for our current leap frame. This is a hack
996 * and ignores the time stamps in the autokey
999 if (sys_leap != LEAP_NOTINSYNC)
1000 leapsec_autokey_tai(ntohl(ep->pkt[0]),
1001 rbufp->recv_time.l_ui, NULL);
1002 tai_leap.tstamp = ep->tstamp;
1003 tai_leap.fstamp = ep->fstamp;
1005 mprintf_event(EVNT_TAI, peer,
1006 "%d seconds", ntohl(ep->pkt[0]));
1007 peer->crypto |= CRYPTO_FLAG_LEAP;
1008 peer->flash &= ~TEST8;
1009 snprintf(statstr, sizeof(statstr),
1010 "leap TAI offset %d at %u expire %u fs %u",
1011 ntohl(ep->pkt[0]), ntohl(ep->pkt[1]),
1012 ntohl(ep->pkt[2]), ntohl(ep->fstamp));
1013 record_crypto_stats(&peer->srcadr, statstr);
1014 DPRINTF(1, ("crypto_recv: %s\n", statstr));
1018 * We come here in symmetric modes for miscellaneous
1019 * commands that have value fields but are processed on
1020 * the transmit side. All we need do here is check for
1021 * valid field length. Note that ASSOC is handled
1030 if (len < VALUE_LEN) {
1037 * We come here in symmetric modes for requests
1038 * requiring a response (above plus AUTO and LEAP) and
1039 * for responses. If a request, save the extension field
1040 * for later; invalid requests will be caught on the
1041 * transmit side. If an error or invalid response,
1042 * declare a protocol error.
1045 if (code & (CRYPTO_RESP | CRYPTO_ERROR)) {
1047 } else if (peer->cmmd == NULL) {
1049 memcpy(fp, ep, len);
1055 * The first error found terminates the extension field
1056 * scan and we return the laundry to the caller.
1058 if (rval != XEVNT_OK) {
1059 snprintf(statstr, sizeof(statstr),
1060 "%04x %d %02x %s", htonl(ep->opcode),
1061 associd, rval, eventstr(rval));
1062 record_crypto_stats(&peer->srcadr, statstr);
1063 DPRINTF(1, ("crypto_recv: %s\n", statstr));
1066 authlen += (len + 3) / 4 * 4;
1073 * crypto_xmit - construct extension fields
1075 * This routine is called both when an association is configured and
1076 * when one is not. The only case where this matters is to retrieve the
1077 * autokey information, in which case the caller has to provide the
1078 * association ID to match the association.
1080 * Side effect: update the packet offset.
1084 * XEVNT_CRT bad or missing certificate
1085 * XEVNT_ERR protocol error
1086 * XEVNT_LEN bad field format or length
1087 * XEVNT_PER host certificate expired
1091 struct peer *peer, /* peer structure pointer */
1092 struct pkt *xpkt, /* transmit packet pointer */
1093 struct recvbuf *rbufp, /* receive buffer pointer */
1094 int start, /* offset to extension field */
1095 struct exten *ep, /* extension pointer */
1096 keyid_t cookie /* session cookie */
1099 struct exten *fp; /* extension pointers */
1100 struct cert_info *cp, *xp, *yp; /* cert info/value pointer */
1101 sockaddr_u *srcadr_sin; /* source address */
1102 u_int32 *pkt; /* packet pointer */
1103 u_int opcode; /* extension field opcode */
1104 char certname[MAXHOSTNAME + 1]; /* subject name buffer */
1105 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1107 struct calendar tscal;
1116 * Generate the requested extension field request code, length
1117 * and association ID. If this is a response and the host is not
1118 * synchronized, light the error bit and go home.
1120 pkt = (u_int32 *)xpkt + start / 4;
1121 fp = (struct exten *)pkt;
1122 opcode = ntohl(ep->opcode);
1124 srcadr_sin = &peer->srcadr;
1125 if (!(opcode & CRYPTO_RESP))
1126 peer->opcode = ep->opcode;
1128 srcadr_sin = &rbufp->recv_srcadr;
1130 associd = (associd_t) ntohl(ep->associd);
1132 fp->opcode = htonl((opcode & 0xffff0000) | len);
1133 fp->associd = ep->associd;
1135 tstamp = crypto_time();
1136 switch (opcode & 0xffff0000) {
1139 * Send association request and response with status word and
1140 * host name. Note, this message is not signed and the filestamp
1141 * contains only the status word.
1144 case CRYPTO_ASSOC | CRYPTO_RESP:
1145 len = crypto_send(fp, &hostval, start);
1146 fp->fstamp = htonl(crypto_flags);
1150 * Send certificate request. Use the values from the extension
1154 memset(&vtemp, 0, sizeof(vtemp));
1155 vtemp.tstamp = ep->tstamp;
1156 vtemp.fstamp = ep->fstamp;
1157 vtemp.vallen = ep->vallen;
1158 vtemp.ptr = (u_char *)ep->pkt;
1159 len = crypto_send(fp, &vtemp, start);
1163 * Send sign request. Use the host certificate, which is self-
1164 * signed and may or may not be trusted.
1167 (void)ntpcal_ntp_to_date(&tscal, tstamp, NULL);
1168 if ((calcomp(&tscal, &(cert_host->first)) < 0)
1169 || (calcomp(&tscal, &(cert_host->last)) > 0))
1172 len = crypto_send(fp, &cert_host->cert, start);
1176 * Send certificate response. Use the name in the extension
1177 * field to find the certificate in the cache. If the request
1178 * contains no subject name, assume the name of this host. This
1179 * is for backwards compatibility. Private certificates are
1182 * There may be several certificates matching the request. First
1183 * choice is a self-signed trusted certificate; second choice is
1184 * any certificate signed by another host. There is no third
1187 case CRYPTO_CERT | CRYPTO_RESP:
1188 vallen = exten_payload_size(ep); /* Must be <64k */
1189 if (vallen == 0 || vallen >= sizeof(certname) ) {
1195 * Find all public valid certificates with matching
1196 * subject. If a self-signed, trusted certificate is
1197 * found, use that certificate. If not, use the last non
1198 * self-signed certificate.
1200 memcpy(certname, ep->pkt, vallen);
1201 certname[vallen] = '\0';
1203 for (cp = cinfo; cp != NULL; cp = cp->link) {
1204 if (cp->flags & (CERT_PRIV | CERT_ERROR))
1207 if (strcmp(certname, cp->subject) != 0)
1210 if (strcmp(certname, cp->issuer) != 0)
1212 else if (cp ->flags & CERT_TRUST)
1218 * Be careful who you trust. If the certificate is not
1219 * found, return an empty response. Note that we dont
1220 * enforce lifetimes here.
1222 * The timestamp and filestamp are taken from the
1223 * certificate value structure. For all certificates the
1224 * timestamp is the latest signature update time. For
1225 * host and imported certificates the filestamp is the
1226 * creation epoch. For signed certificates the filestamp
1227 * is the creation epoch of the trusted certificate at
1228 * the root of the certificate trail. In principle, this
1229 * allows strong checking for signature masquerade.
1239 len = crypto_send(fp, &xp->cert, start);
1243 * Send challenge in Schnorr (IFF) identity scheme.
1247 break; /* hack attack */
1249 if ((rval = crypto_alice(peer, &vtemp)) == XEVNT_OK) {
1250 len = crypto_send(fp, &vtemp, start);
1256 * Send response in Schnorr (IFF) identity scheme.
1258 case CRYPTO_IFF | CRYPTO_RESP:
1259 if ((rval = crypto_bob(ep, &vtemp)) == XEVNT_OK) {
1260 len = crypto_send(fp, &vtemp, start);
1266 * Send challenge in Guillou-Quisquater (GQ) identity scheme.
1270 break; /* hack attack */
1272 if ((rval = crypto_alice2(peer, &vtemp)) == XEVNT_OK) {
1273 len = crypto_send(fp, &vtemp, start);
1279 * Send response in Guillou-Quisquater (GQ) identity scheme.
1281 case CRYPTO_GQ | CRYPTO_RESP:
1282 if ((rval = crypto_bob2(ep, &vtemp)) == XEVNT_OK) {
1283 len = crypto_send(fp, &vtemp, start);
1289 * Send challenge in MV identity scheme.
1293 break; /* hack attack */
1295 if ((rval = crypto_alice3(peer, &vtemp)) == XEVNT_OK) {
1296 len = crypto_send(fp, &vtemp, start);
1302 * Send response in MV identity scheme.
1304 case CRYPTO_MV | CRYPTO_RESP:
1305 if ((rval = crypto_bob3(ep, &vtemp)) == XEVNT_OK) {
1306 len = crypto_send(fp, &vtemp, start);
1312 * Send certificate sign response. The integrity of the request
1313 * certificate has already been verified on the receive side.
1314 * Sign the response using the local server key. Use the
1315 * filestamp from the request and use the timestamp as the
1316 * current time. Light the error bit if the certificate is
1317 * invalid or contains an unverified signature.
1319 case CRYPTO_SIGN | CRYPTO_RESP:
1320 if ((rval = cert_sign(ep, &vtemp)) == XEVNT_OK) {
1321 len = crypto_send(fp, &vtemp, start);
1327 * Send public key and signature. Use the values from the public
1331 len = crypto_send(fp, &pubkey, start);
1335 * Encrypt and send cookie and signature. Light the error bit if
1336 * anything goes wrong.
1338 case CRYPTO_COOK | CRYPTO_RESP:
1339 vallen = ntohl(ep->vallen); /* Must be <64k */
1341 || (vallen >= MAX_VALLEN)
1342 || (opcode & 0x0000ffff) < VALUE_LEN + vallen) {
1349 tcookie = peer->hcookie;
1350 if ((rval = crypto_encrypt((const u_char *)ep->pkt, vallen, &tcookie, &vtemp))
1352 len = crypto_send(fp, &vtemp, start);
1358 * Find peer and send autokey data and signature in broadcast
1359 * server and symmetric modes. Use the values in the autokey
1360 * structure. If no association is found, either the server has
1361 * restarted with new associations or some perp has replayed an
1362 * old message, in which case light the error bit.
1364 case CRYPTO_AUTO | CRYPTO_RESP:
1366 if ((peer = findpeerbyassoc(associd)) == NULL) {
1371 peer->flags &= ~FLAG_ASSOC;
1372 len = crypto_send(fp, &peer->sndval, start);
1376 * Send leapseconds values and signature. Use the values from
1377 * the tai structure. If no table has been loaded, just send an
1380 case CRYPTO_LEAP | CRYPTO_RESP:
1381 len = crypto_send(fp, &tai_leap, start);
1385 * Default - Send a valid command for unknown requests; send
1386 * an error response for unknown resonses.
1389 if (opcode & CRYPTO_RESP)
1394 * In case of error, flame the log. If a request, toss the
1395 * puppy; if a response, return so the sender can flame, too.
1397 if (rval != XEVNT_OK) {
1400 uint32 = CRYPTO_ERROR;
1402 fp->opcode |= htonl(uint32);
1403 snprintf(statstr, sizeof(statstr),
1404 "%04x %d %02x %s", opcode, associd, rval,
1406 record_crypto_stats(srcadr_sin, statstr);
1407 DPRINTF(1, ("crypto_xmit: %s\n", statstr));
1408 if (!(opcode & CRYPTO_RESP))
1411 DPRINTF(1, ("crypto_xmit: flags 0x%x offset %d len %d code 0x%x associd %d\n",
1412 crypto_flags, start, len, opcode >> 16, associd));
1418 * crypto_verify - verify the extension field value and signature
1422 * XEVNT_ERR protocol error
1423 * XEVNT_FSP bad filestamp
1424 * XEVNT_LEN bad field format or length
1425 * XEVNT_PUB bad or missing public key
1426 * XEVNT_SGL bad signature length
1427 * XEVNT_SIG signature not verified
1428 * XEVNT_TSP bad timestamp
1432 struct exten *ep, /* extension pointer */
1433 struct value *vp, /* value pointer */
1434 struct peer *peer /* peer structure pointer */
1437 EVP_PKEY *pkey; /* server public key */
1438 EVP_MD_CTX *ctx; /* signature context */
1439 tstamp_t tstamp, tstamp1 = 0; /* timestamp */
1440 tstamp_t fstamp, fstamp1 = 0; /* filestamp */
1441 u_int vallen; /* value length */
1442 u_int siglen; /* signature length */
1447 * We are extremely parannoyed. We require valid opcode, length,
1448 * association ID, timestamp, filestamp, public key, digest,
1449 * signature length and signature, where relevant. Note that
1450 * preliminary length checks are done in the main loop.
1452 len = ntohl(ep->opcode) & 0x0000ffff;
1453 opcode = ntohl(ep->opcode) & 0xffff0000;
1456 * Check for valid value header, association ID and extension
1457 * field length. Remember, it is not an error to receive an
1458 * unsolicited response; however, the response ID must match
1459 * the association ID.
1461 if (opcode & CRYPTO_ERROR)
1464 if (len < VALUE_LEN)
1467 if (opcode == (CRYPTO_AUTO | CRYPTO_RESP) && (peer->pmode ==
1468 MODE_BROADCAST || (peer->cast_flags & MDF_BCLNT))) {
1469 if (ntohl(ep->associd) != peer->assoc)
1472 if (ntohl(ep->associd) != peer->associd)
1477 * We have a valid value header. Check for valid value and
1478 * signature field lengths. The extension field length must be
1479 * long enough to contain the value header, value and signature.
1480 * Note both the value and signature field lengths are rounded
1481 * up to the next word (4 octets).
1483 vallen = ntohl(ep->vallen);
1485 || vallen > MAX_VALLEN)
1488 i = (vallen + 3) / 4;
1489 siglen = ntohl(ep->pkt[i]);
1491 if ( siglen > MAX_VALLEN
1492 || len - VALUE_LEN < ((vallen + 3) / 4) * 4
1493 || len - VALUE_LEN - ((vallen + 3) / 4) * 4
1494 < ((siglen + 3) / 4) * 4)
1498 * Check for valid timestamp and filestamp. If the timestamp is
1499 * zero, the sender is not synchronized and signatures are
1500 * not possible. If nonzero the timestamp must not precede the
1501 * filestamp. The timestamp and filestamp must not precede the
1502 * corresponding values in the value structure, if present.
1504 tstamp = ntohl(ep->tstamp);
1505 fstamp = ntohl(ep->fstamp);
1509 if (tstamp < fstamp)
1513 tstamp1 = ntohl(vp->tstamp);
1514 fstamp1 = ntohl(vp->fstamp);
1515 if (tstamp1 != 0 && fstamp1 != 0) {
1516 if (tstamp < tstamp1)
1519 if ((tstamp < fstamp1 || fstamp < fstamp1))
1525 * At the time the certificate message is validated, the public
1526 * key in the message is not available. Thus, don't try to
1527 * verify the signature.
1529 if (opcode == (CRYPTO_CERT | CRYPTO_RESP))
1533 * Check for valid signature length, public key and digest
1536 if (crypto_flags & peer->crypto & CRYPTO_FLAG_PRIV)
1540 if (siglen == 0 || pkey == NULL || peer->digest == NULL)
1543 if (siglen != (u_int)EVP_PKEY_size(pkey))
1547 * Darn, I thought we would never get here. Verify the
1548 * signature. If the identity exchange is verified, light the
1549 * proventic bit. What a relief.
1551 ctx = EVP_MD_CTX_new();
1552 EVP_VerifyInit(ctx, peer->digest);
1553 /* XXX: the "+ 12" needs to be at least documented... */
1554 EVP_VerifyUpdate(ctx, (u_char *)&ep->tstamp, vallen + 12);
1555 if (EVP_VerifyFinal(ctx, (u_char *)&ep->pkt[i], siglen,
1557 EVP_MD_CTX_free(ctx);
1560 EVP_MD_CTX_free(ctx);
1562 if (peer->crypto & CRYPTO_FLAG_VRFY)
1563 peer->crypto |= CRYPTO_FLAG_PROV;
1569 * crypto_encrypt - construct vp (encrypted cookie and signature) from
1570 * the public key and cookie.
1574 * XEVNT_CKY bad or missing cookie
1575 * XEVNT_PUB bad or missing public key
1579 const u_char *ptr, /* Public Key */
1580 u_int vallen, /* Length of Public Key */
1581 keyid_t *cookie, /* server cookie */
1582 struct value *vp /* value pointer */
1585 EVP_PKEY *pkey; /* public key */
1586 EVP_MD_CTX *ctx; /* signature context */
1587 tstamp_t tstamp; /* NTP timestamp */
1592 * Extract the public key from the request.
1594 pkey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &ptr, vallen);
1596 msyslog(LOG_ERR, "crypto_encrypt: %s",
1597 ERR_error_string(ERR_get_error(), NULL));
1602 * Encrypt the cookie, encode in ASN.1 and sign.
1604 memset(vp, 0, sizeof(struct value));
1605 tstamp = crypto_time();
1606 vp->tstamp = htonl(tstamp);
1607 vp->fstamp = hostval.tstamp;
1608 vallen = EVP_PKEY_size(pkey);
1609 vp->vallen = htonl(vallen);
1610 vp->ptr = emalloc(vallen);
1612 temp32 = htonl(*cookie);
1613 if (RSA_public_encrypt(4, (u_char *)&temp32, puch,
1614 EVP_PKEY_get0_RSA(pkey), RSA_PKCS1_OAEP_PADDING) <= 0) {
1615 msyslog(LOG_ERR, "crypto_encrypt: %s",
1616 ERR_error_string(ERR_get_error(), NULL));
1618 EVP_PKEY_free(pkey);
1621 EVP_PKEY_free(pkey);
1625 vp->sig = emalloc(sign_siglen);
1626 ctx = EVP_MD_CTX_new();
1627 EVP_SignInit(ctx, sign_digest);
1628 EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
1629 EVP_SignUpdate(ctx, vp->ptr, vallen);
1630 if (EVP_SignFinal(ctx, vp->sig, &vallen, sign_pkey)) {
1631 INSIST(vallen <= sign_siglen);
1632 vp->siglen = htonl(vallen);
1634 EVP_MD_CTX_free(ctx);
1640 * crypto_ident - construct extension field for identity scheme
1642 * This routine determines which identity scheme is in use and
1643 * constructs an extension field for that scheme.
1646 * CRYTPO_IFF IFF scheme
1647 * CRYPTO_GQ GQ scheme
1648 * CRYPTO_MV MV scheme
1649 * CRYPTO_NULL no available scheme
1653 struct peer *peer /* peer structure pointer */
1656 char filename[MAXFILENAME];
1657 const char * scheme_name;
1661 * We come here after the group trusted host has been found; its
1662 * name defines the group name. Search the key cache for all
1663 * keys matching the same group name in order IFF, GQ and MV.
1664 * Use the first one available.
1667 if (peer->crypto & CRYPTO_FLAG_IFF) {
1668 scheme_name = "iff";
1669 scheme_id = CRYPTO_IFF;
1670 } else if (peer->crypto & CRYPTO_FLAG_GQ) {
1672 scheme_id = CRYPTO_GQ;
1673 } else if (peer->crypto & CRYPTO_FLAG_MV) {
1675 scheme_id = CRYPTO_MV;
1678 if (scheme_name != NULL) {
1679 snprintf(filename, sizeof(filename), "ntpkey_%spar_%s",
1680 scheme_name, peer->ident);
1681 peer->ident_pkey = crypto_key(filename, NULL,
1683 if (peer->ident_pkey != NULL)
1688 "crypto_ident: no identity parameters found for group %s",
1696 * crypto_args - construct extension field from arguments
1698 * This routine creates an extension field with current timestamps and
1699 * specified opcode, association ID and optional string. Note that the
1700 * extension field is created here, but freed after the crypto_xmit()
1701 * call in the protocol module.
1703 * Returns extension field pointer (no errors)
1705 * XXX: opcode and len should really be 32-bit quantities and
1706 * we should make sure that str is not too big.
1710 struct peer *peer, /* peer structure pointer */
1711 u_int opcode, /* operation code */
1712 associd_t associd, /* association ID */
1713 char *str /* argument string */
1716 tstamp_t tstamp; /* NTP timestamp */
1717 struct exten *ep; /* extension field pointer */
1718 u_int len; /* extension field length */
1721 tstamp = crypto_time();
1722 len = sizeof(struct exten);
1725 INSIST(slen < MAX_VALLEN);
1728 ep = emalloc_zero(len);
1732 REQUIRE(0 == (len & ~0x0000ffff));
1733 REQUIRE(0 == (opcode & ~0xffff0000));
1735 ep->opcode = htonl(opcode + len);
1736 ep->associd = htonl(associd);
1737 ep->tstamp = htonl(tstamp);
1738 ep->fstamp = hostval.tstamp;
1741 ep->vallen = htonl(slen);
1742 memcpy((char *)ep->pkt, str, slen);
1749 * crypto_send - construct extension field from value components
1751 * The value and signature fields are zero-padded to a word boundary.
1752 * Note: it is not polite to send a nonempty signature with zero
1753 * timestamp or a nonzero timestamp with an empty signature, but those
1754 * rules are not enforced here.
1756 * XXX This code won't work on a box with 16-bit ints.
1760 struct exten *ep, /* extension field pointer */
1761 struct value *vp, /* value pointer */
1762 int start /* buffer offset */
1765 u_int len, vallen, siglen, opcode;
1769 * Calculate extension field length and check for buffer
1770 * overflow. Leave room for the MAC.
1772 len = 16; /* XXX Document! */
1773 vallen = ntohl(vp->vallen);
1774 INSIST(vallen <= MAX_VALLEN);
1775 len += ((vallen + 3) / 4 + 1) * 4;
1776 siglen = ntohl(vp->siglen);
1777 len += ((siglen + 3) / 4 + 1) * 4;
1778 if (start + len > sizeof(struct pkt) - MAX_MAC_LEN)
1784 ep->tstamp = vp->tstamp;
1785 ep->fstamp = vp->fstamp;
1786 ep->vallen = vp->vallen;
1789 * Copy value. If the data field is empty or zero length,
1790 * encode an empty value with length zero.
1793 if (vallen > 0 && vp->ptr != NULL) {
1796 ep->pkt[i + j++] = 0;
1797 memcpy(&ep->pkt[i], vp->ptr, vallen);
1802 * Copy signature. If the signature field is empty or zero
1803 * length, encode an empty signature with length zero.
1805 ep->pkt[i++] = vp->siglen;
1806 if (siglen > 0 && vp->sig != NULL) {
1809 ep->pkt[i + j++] = 0;
1810 memcpy(&ep->pkt[i], vp->sig, siglen);
1811 /* i += j; */ /* We don't use i after this */
1813 opcode = ntohl(ep->opcode);
1814 ep->opcode = htonl((opcode & 0xffff0000) | len);
1815 ENSURE(len <= MAX_VALLEN);
1821 * crypto_update - compute new public value and sign extension fields
1823 * This routine runs periodically, like once a day, and when something
1824 * changes. It updates the timestamps on three value structures and one
1825 * value structure list, then signs all the structures:
1827 * hostval host name (not signed)
1829 * cinfo certificate info/value list
1830 * tai_leap leap values
1832 * Filestamps are proventic data, so this routine runs only when the
1833 * host is synchronized to a proventicated source. Thus, the timestamp
1834 * is proventic and can be used to deflect clogging attacks.
1836 * Returns void (no errors)
1841 EVP_MD_CTX *ctx; /* message digest context */
1842 struct cert_info *cp; /* certificate info/value */
1843 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1846 leap_result_t leap_data;
1848 hostval.tstamp = htonl(crypto_time());
1849 if (hostval.tstamp == 0)
1852 ctx = EVP_MD_CTX_new();
1855 * Sign public key and timestamps. The filestamp is derived from
1856 * the host key file extension from wherever the file was
1859 if (pubkey.vallen != 0) {
1860 pubkey.tstamp = hostval.tstamp;
1862 if (pubkey.sig == NULL)
1863 pubkey.sig = emalloc(sign_siglen);
1864 EVP_SignInit(ctx, sign_digest);
1865 EVP_SignUpdate(ctx, (u_char *)&pubkey, 12);
1866 EVP_SignUpdate(ctx, pubkey.ptr, ntohl(pubkey.vallen));
1867 if (EVP_SignFinal(ctx, pubkey.sig, &len, sign_pkey)) {
1868 INSIST(len <= sign_siglen);
1869 pubkey.siglen = htonl(len);
1874 * Sign certificates and timestamps. The filestamp is derived
1875 * from the certificate file extension from wherever the file
1876 * was generated. Note we do not throw expired certificates
1877 * away; they may have signed younger ones.
1879 for (cp = cinfo; cp != NULL; cp = cp->link) {
1880 cp->cert.tstamp = hostval.tstamp;
1881 cp->cert.siglen = 0;
1882 if (cp->cert.sig == NULL)
1883 cp->cert.sig = emalloc(sign_siglen);
1884 EVP_SignInit(ctx, sign_digest);
1885 EVP_SignUpdate(ctx, (u_char *)&cp->cert, 12);
1886 EVP_SignUpdate(ctx, cp->cert.ptr,
1887 ntohl(cp->cert.vallen));
1888 if (EVP_SignFinal(ctx, cp->cert.sig, &len, sign_pkey)) {
1889 INSIST(len <= sign_siglen);
1890 cp->cert.siglen = htonl(len);
1895 * Sign leapseconds values and timestamps. Note it is not an
1896 * error to return null values.
1898 tai_leap.tstamp = hostval.tstamp;
1899 tai_leap.fstamp = hostval.fstamp;
1901 /* Get the leap second era. We might need a full lookup early
1902 * after start, when the cache is not yet loaded.
1904 leapsec_frame(&leap_data);
1905 if ( ! memcmp(&leap_data.ebase, &leap_data.ttime, sizeof(vint64))) {
1906 time_t now = time(NULL);
1907 uint32_t nowntp = (uint32_t)now + JAN_1970;
1908 leapsec_query(&leap_data, nowntp, &now);
1911 /* Create the data block. The protocol does not work without. */
1912 len = 3 * sizeof(u_int32);
1913 if (tai_leap.ptr == NULL || ntohl(tai_leap.vallen) != len) {
1915 tai_leap.ptr = emalloc(len);
1916 tai_leap.vallen = htonl(len);
1918 ptr = (u_int32 *)tai_leap.ptr;
1919 if (leap_data.tai_offs > 10) {
1920 /* create a TAI / leap era block. The end time is a
1921 * fake -- maybe we can do better.
1923 ptr[0] = htonl(leap_data.tai_offs);
1924 ptr[1] = htonl(leap_data.ebase.d_s.lo);
1925 if (leap_data.ttime.d_s.hi >= 0)
1926 ptr[2] = htonl(leap_data.ttime.D_s.lo + 7*86400);
1928 ptr[2] = htonl(leap_data.ebase.D_s.lo + 25*86400);
1930 /* no leap era available */
1931 memset(ptr, 0, len);
1933 if (tai_leap.sig == NULL)
1934 tai_leap.sig = emalloc(sign_siglen);
1935 EVP_SignInit(ctx, sign_digest);
1936 EVP_SignUpdate(ctx, (u_char *)&tai_leap, 12);
1937 EVP_SignUpdate(ctx, tai_leap.ptr, len);
1938 if (EVP_SignFinal(ctx, tai_leap.sig, &len, sign_pkey)) {
1939 INSIST(len <= sign_siglen);
1940 tai_leap.siglen = htonl(len);
1942 crypto_flags |= CRYPTO_FLAG_TAI;
1944 snprintf(statstr, sizeof(statstr), "signature update ts %u",
1945 ntohl(hostval.tstamp));
1946 record_crypto_stats(NULL, statstr);
1947 DPRINTF(1, ("crypto_update: %s\n", statstr));
1948 EVP_MD_CTX_free(ctx);
1952 * crypto_update_taichange - eventually trigger crypto_update
1954 * This is called when a change in 'sys_tai' is detected. This will
1955 * happen shortly after a leap second is detected, but unhappily also
1956 * early after system start; also, the crypto stuff might be unused and
1957 * an unguarded call to crypto_update() causes a crash.
1959 * This function makes sure that there already *is* a valid crypto block
1960 * for the use with autokey, and only calls 'crypto_update()' if it can
1963 * Returns void (no errors)
1966 crypto_update_taichange(void)
1968 static const u_int len = 3 * sizeof(u_int32);
1970 /* check if the signing digest algo is available */
1971 if (sign_digest == NULL || sign_pkey == NULL)
1974 /* check size of TAI extension block */
1975 if (tai_leap.ptr == NULL || ntohl(tai_leap.vallen) != len)
1978 /* crypto_update should at least not crash here! */
1983 * value_free - free value structure components.
1985 * Returns void (no errors)
1989 struct value *vp /* value structure */
1992 if (vp->ptr != NULL)
1994 if (vp->sig != NULL)
1996 memset(vp, 0, sizeof(struct value));
2001 * crypto_time - returns current NTP time.
2003 * Returns NTP seconds if in synch, 0 otherwise
2008 l_fp tstamp; /* NTP time */
2011 if (sys_leap != LEAP_NOTINSYNC)
2012 get_systime(&tstamp);
2013 return (tstamp.l_ui);
2018 * asn_to_calendar - convert ASN1_TIME time structure to struct calendar.
2024 const ASN1_TIME *asn1time, /* pointer to ASN1_TIME structure */
2025 struct calendar *pjd /* pointer to result */
2028 size_t len; /* length of ASN1_TIME string */
2029 char v[24]; /* writable copy of ASN1_TIME string */
2030 unsigned long temp; /* result from strtoul */
2033 * Extract time string YYMMDDHHMMSSZ from ASN1 time structure.
2034 * Or YYYYMMDDHHMMSSZ.
2035 * Note that the YY, MM, DD fields start with one, the HH, MM,
2036 * SS fields start with zero and the Z character is ignored.
2037 * Also note that two-digit years less than 50 map to years greater than
2038 * 100. Dontcha love ASN.1? Better than MIL-188.
2040 len = asn1time->length;
2041 REQUIRE(len < sizeof(v));
2042 (void)strncpy(v, (char *)(asn1time->data), len);
2044 temp = strtoul(v+len-3, NULL, 10);
2048 temp = strtoul(v+len-5, NULL, 10);
2052 temp = strtoul(v+len-7, NULL, 10);
2056 temp = strtoul(v+len-9, NULL, 10);
2057 pjd->monthday = temp;
2060 temp = strtoul(v+len-11, NULL, 10);
2064 temp = strtoul(v, NULL, 10);
2065 /* handle two-digit years */
2072 pjd->yearday = pjd->weekday = 0;
2078 * bigdig() - compute a BIGNUM MD5 hash of a BIGNUM number.
2080 * Returns void (no errors)
2084 BIGNUM *bn, /* BIGNUM * from */
2085 BIGNUM *bk /* BIGNUM * to */
2088 EVP_MD_CTX *ctx; /* message digest context */
2089 u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
2090 u_char *ptr; /* a BIGNUM as binary string */
2093 len = BN_num_bytes(bn);
2096 ctx = EVP_MD_CTX_new();
2097 # if defined(OPENSSL) && defined(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW)
2098 /* [Bug 3457] set flags and don't kill them again */
2099 EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
2100 EVP_DigestInit_ex(ctx, EVP_md5(), NULL);
2102 EVP_DigestInit(ctx, EVP_md5());
2104 EVP_DigestUpdate(ctx, ptr, len);
2105 EVP_DigestFinal(ctx, dgst, &len);
2106 EVP_MD_CTX_free(ctx);
2107 BN_bin2bn(dgst, len, bk);
2113 ***********************************************************************
2115 * The following routines implement the Schnorr (IFF) identity scheme *
2117 ***********************************************************************
2119 * The Schnorr (IFF) identity scheme is intended for use when
2120 * certificates are generated by some other trusted certificate
2121 * authority and the certificate cannot be used to convey public
2122 * parameters. There are two kinds of files: encrypted server files that
2123 * contain private and public values and nonencrypted client files that
2124 * contain only public values. New generations of server files must be
2125 * securely transmitted to all servers of the group; client files can be
2126 * distributed by any means. The scheme is self contained and
2127 * independent of new generations of host keys, sign keys and
2130 * The IFF values hide in a DSA cuckoo structure which uses the same
2131 * parameters. The values are used by an identity scheme based on DSA
2132 * cryptography and described in Stimson p. 285. The p is a 512-bit
2133 * prime, g a generator of Zp* and q a 160-bit prime that divides p - 1
2134 * and is a qth root of 1 mod p; that is, g^q = 1 mod p. The TA rolls a
2135 * private random group key b (0 < b < q) and public key v = g^b, then
2136 * sends (p, q, g, b) to the servers and (p, q, g, v) to the clients.
2137 * Alice challenges Bob to confirm identity using the protocol described
2142 * The scheme goes like this. Both Alice and Bob have the public primes
2143 * p, q and generator g. The TA gives private key b to Bob and public
2146 * Alice rolls new random challenge r (o < r < q) and sends to Bob in
2147 * the IFF request message. Bob rolls new random k (0 < k < q), then
2148 * computes y = k + b r mod q and x = g^k mod p and sends (y, hash(x))
2149 * to Alice in the response message. Besides making the response
2150 * shorter, the hash makes it effectivey impossible for an intruder to
2151 * solve for b by observing a number of these messages.
2153 * Alice receives the response and computes g^y v^r mod p. After a bit
2154 * of algebra, this simplifies to g^k. If the hash of this result
2155 * matches hash(x), Alice knows that Bob has the group key b. The signed
2156 * response binds this knowledge to Bob's private key and the public key
2157 * previously received in his certificate.
2159 * crypto_alice - construct Alice's challenge in IFF scheme
2163 * XEVNT_ID bad or missing group key
2164 * XEVNT_PUB bad or missing public key
2168 struct peer *peer, /* peer pointer */
2169 struct value *vp /* value pointer */
2172 DSA *dsa; /* IFF parameters */
2173 BN_CTX *bctx; /* BIGNUM context */
2174 EVP_MD_CTX *ctx; /* signature context */
2180 * The identity parameters must have correct format and content.
2182 if (peer->ident_pkey == NULL) {
2183 msyslog(LOG_NOTICE, "crypto_alice: scheme unavailable");
2187 if ((dsa = EVP_PKEY_get0_DSA(peer->ident_pkey->pkey)) == NULL) {
2188 msyslog(LOG_NOTICE, "crypto_alice: defective key");
2193 * Roll new random r (0 < r < q).
2195 if (peer->iffval != NULL)
2196 BN_free(peer->iffval);
2197 peer->iffval = BN_new();
2198 DSA_get0_pqg(dsa, NULL, &q, NULL);
2199 len = BN_num_bytes(q);
2200 BN_rand(peer->iffval, len * 8, -1, 1); /* r mod q*/
2201 bctx = BN_CTX_new();
2202 BN_mod(peer->iffval, peer->iffval, q, bctx);
2206 * Sign and send to Bob. The filestamp is from the local file.
2208 memset(vp, 0, sizeof(struct value));
2209 tstamp = crypto_time();
2210 vp->tstamp = htonl(tstamp);
2211 vp->fstamp = htonl(peer->ident_pkey->fstamp);
2212 vp->vallen = htonl(len);
2213 vp->ptr = emalloc(len);
2214 BN_bn2bin(peer->iffval, vp->ptr);
2218 vp->sig = emalloc(sign_siglen);
2219 ctx = EVP_MD_CTX_new();
2220 EVP_SignInit(ctx, sign_digest);
2221 EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
2222 EVP_SignUpdate(ctx, vp->ptr, len);
2223 if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
2224 INSIST(len <= sign_siglen);
2225 vp->siglen = htonl(len);
2227 EVP_MD_CTX_free(ctx);
2233 * crypto_bob - construct Bob's response to Alice's challenge
2237 * XEVNT_ERR protocol error
2238 * XEVNT_ID bad or missing group key
2242 struct exten *ep, /* extension pointer */
2243 struct value *vp /* value pointer */
2246 DSA *dsa; /* IFF parameters */
2247 DSA_SIG *sdsa; /* DSA signature context fake */
2248 BN_CTX *bctx; /* BIGNUM context */
2249 EVP_MD_CTX *ctx; /* signature context */
2250 tstamp_t tstamp; /* NTP timestamp */
2251 BIGNUM *bn, *bk, *r;
2253 u_int len; /* extension field value length */
2254 const BIGNUM *p, *q, *g;
2255 const BIGNUM *priv_key;
2258 * If the IFF parameters are not valid, something awful
2259 * happened or we are being tormented.
2261 if (iffkey_info == NULL) {
2262 msyslog(LOG_NOTICE, "crypto_bob: scheme unavailable");
2265 dsa = EVP_PKEY_get0_DSA(iffkey_info->pkey);
2266 DSA_get0_pqg(dsa, &p, &q, &g);
2267 DSA_get0_key(dsa, NULL, &priv_key);
2270 * Extract r from the challenge.
2272 len = exten_payload_size(ep);
2273 if (len == 0 || len > MAX_VALLEN)
2275 if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2276 msyslog(LOG_ERR, "crypto_bob: %s",
2277 ERR_error_string(ERR_get_error(), NULL));
2282 * Bob rolls random k (0 < k < q), computes y = k + b r mod q
2283 * and x = g^k mod p, then sends (y, hash(x)) to Alice.
2285 bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2286 sdsa = DSA_SIG_new();
2287 BN_rand(bk, len * 8, -1, 1); /* k */
2288 BN_mod_mul(bn, priv_key, r, q, bctx); /* b r mod q */
2290 BN_mod(bn, bn, q, bctx); /* k + b r mod q */
2291 BN_mod_exp(bk, g, bk, p, bctx); /* g^k mod p */
2293 DSA_SIG_set0(sdsa, bn, bk);
2298 DSA_print_fp(stdout, dsa, 0);
2302 * Encode the values in ASN.1 and sign. The filestamp is from
2305 len = i2d_DSA_SIG(sdsa, NULL);
2307 msyslog(LOG_ERR, "crypto_bob: %s",
2308 ERR_error_string(ERR_get_error(), NULL));
2312 if (len > MAX_VALLEN) {
2313 msyslog(LOG_ERR, "crypto_bob: signature is too big: %u",
2318 memset(vp, 0, sizeof(struct value));
2319 tstamp = crypto_time();
2320 vp->tstamp = htonl(tstamp);
2321 vp->fstamp = htonl(iffkey_info->fstamp);
2322 vp->vallen = htonl(len);
2325 i2d_DSA_SIG(sdsa, &ptr);
2330 /* XXX: more validation to make sure the sign fits... */
2331 vp->sig = emalloc(sign_siglen);
2332 ctx = EVP_MD_CTX_new();
2333 EVP_SignInit(ctx, sign_digest);
2334 EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
2335 EVP_SignUpdate(ctx, vp->ptr, len);
2336 if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
2337 INSIST(len <= sign_siglen);
2338 vp->siglen = htonl(len);
2340 EVP_MD_CTX_free(ctx);
2346 * crypto_iff - verify Bob's response to Alice's challenge
2350 * XEVNT_FSP bad filestamp
2351 * XEVNT_ID bad or missing group key
2352 * XEVNT_PUB bad or missing public key
2356 struct exten *ep, /* extension pointer */
2357 struct peer *peer /* peer structure pointer */
2360 DSA *dsa; /* IFF parameters */
2361 BN_CTX *bctx; /* BIGNUM context */
2362 DSA_SIG *sdsa; /* DSA parameters */
2367 const BIGNUM *p, *g;
2368 const BIGNUM *r, *s;
2369 const BIGNUM *pub_key;
2372 * If the IFF parameters are not valid or no challenge was sent,
2373 * something awful happened or we are being tormented.
2375 if (peer->ident_pkey == NULL) {
2376 msyslog(LOG_NOTICE, "crypto_iff: scheme unavailable");
2379 if (ntohl(ep->fstamp) != peer->ident_pkey->fstamp) {
2380 msyslog(LOG_NOTICE, "crypto_iff: invalid filestamp %u",
2384 if ((dsa = EVP_PKEY_get0_DSA(peer->ident_pkey->pkey)) == NULL) {
2385 msyslog(LOG_NOTICE, "crypto_iff: defective key");
2388 if (peer->iffval == NULL) {
2389 msyslog(LOG_NOTICE, "crypto_iff: missing challenge");
2394 * Extract the k + b r and g^k values from the response.
2396 bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2397 len = ntohl(ep->vallen);
2398 ptr = (u_char *)ep->pkt;
2399 if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2400 BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
2401 msyslog(LOG_ERR, "crypto_iff: %s",
2402 ERR_error_string(ERR_get_error(), NULL));
2407 * Compute g^(k + b r) g^(q - b)r mod p.
2409 DSA_get0_key(dsa, &pub_key, NULL);
2410 DSA_get0_pqg(dsa, &p, NULL, &g);
2411 DSA_SIG_get0(sdsa, &r, &s);
2412 BN_mod_exp(bn, pub_key, peer->iffval, p, bctx);
2413 BN_mod_exp(bk, g, r, p, bctx);
2414 BN_mod_mul(bn, bn, bk, p, bctx);
2417 * Verify the hash of the result matches hash(x).
2420 temp = BN_cmp(bn, s);
2421 BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
2422 BN_free(peer->iffval);
2423 peer->iffval = NULL;
2428 msyslog(LOG_NOTICE, "crypto_iff: identity not verified");
2434 ***********************************************************************
2436 * The following routines implement the Guillou-Quisquater (GQ) *
2439 ***********************************************************************
2441 * The Guillou-Quisquater (GQ) identity scheme is intended for use when
2442 * the certificate can be used to convey public parameters. The scheme
2443 * uses a X509v3 certificate extension field do convey the public key of
2444 * a private key known only to servers. There are two kinds of files:
2445 * encrypted server files that contain private and public values and
2446 * nonencrypted client files that contain only public values. New
2447 * generations of server files must be securely transmitted to all
2448 * servers of the group; client files can be distributed by any means.
2449 * The scheme is self contained and independent of new generations of
2450 * host keys and sign keys. The scheme is self contained and independent
2451 * of new generations of host keys and sign keys.
2453 * The GQ parameters hide in a RSA cuckoo structure which uses the same
2454 * parameters. The values are used by an identity scheme based on RSA
2455 * cryptography and described in Stimson p. 300 (with errors). The 512-
2456 * bit public modulus is n = p q, where p and q are secret large primes.
2457 * The TA rolls private random group key b as RSA exponent. These values
2458 * are known to all group members.
2460 * When rolling new certificates, a server recomputes the private and
2461 * public keys. The private key u is a random roll, while the public key
2462 * is the inverse obscured by the group key v = (u^-1)^b. These values
2463 * replace the private and public keys normally generated by the RSA
2464 * scheme. Alice challenges Bob to confirm identity using the protocol
2469 * The scheme goes like this. Both Alice and Bob have the same modulus n
2470 * and some random b as the group key. These values are computed and
2471 * distributed in advance via secret means, although only the group key
2472 * b is truly secret. Each has a private random private key u and public
2473 * key (u^-1)^b, although not necessarily the same ones. Bob and Alice
2474 * can regenerate the key pair from time to time without affecting
2475 * operations. The public key is conveyed on the certificate in an
2476 * extension field; the private key is never revealed.
2478 * Alice rolls new random challenge r and sends to Bob in the GQ
2479 * request message. Bob rolls new random k, then computes y = k u^r mod
2480 * n and x = k^b mod n and sends (y, hash(x)) to Alice in the response
2481 * message. Besides making the response shorter, the hash makes it
2482 * effectivey impossible for an intruder to solve for b by observing
2483 * a number of these messages.
2485 * Alice receives the response and computes y^b v^r mod n. After a bit
2486 * of algebra, this simplifies to k^b. If the hash of this result
2487 * matches hash(x), Alice knows that Bob has the group key b. The signed
2488 * response binds this knowledge to Bob's private key and the public key
2489 * previously received in his certificate.
2491 * crypto_alice2 - construct Alice's challenge in GQ scheme
2495 * XEVNT_ID bad or missing group key
2496 * XEVNT_PUB bad or missing public key
2500 struct peer *peer, /* peer pointer */
2501 struct value *vp /* value pointer */
2504 RSA *rsa; /* GQ parameters */
2505 BN_CTX *bctx; /* BIGNUM context */
2506 EVP_MD_CTX *ctx; /* signature context */
2512 * The identity parameters must have correct format and content.
2514 if (peer->ident_pkey == NULL)
2517 if ((rsa = EVP_PKEY_get0_RSA(peer->ident_pkey->pkey)) == NULL) {
2518 msyslog(LOG_NOTICE, "crypto_alice2: defective key");
2523 * Roll new random r (0 < r < n).
2525 if (peer->iffval != NULL)
2526 BN_free(peer->iffval);
2527 peer->iffval = BN_new();
2528 RSA_get0_key(rsa, &n, NULL, NULL);
2529 len = BN_num_bytes(n);
2530 BN_rand(peer->iffval, len * 8, -1, 1); /* r mod n */
2531 bctx = BN_CTX_new();
2532 BN_mod(peer->iffval, peer->iffval, n, bctx);
2536 * Sign and send to Bob. The filestamp is from the local file.
2538 memset(vp, 0, sizeof(struct value));
2539 tstamp = crypto_time();
2540 vp->tstamp = htonl(tstamp);
2541 vp->fstamp = htonl(peer->ident_pkey->fstamp);
2542 vp->vallen = htonl(len);
2543 vp->ptr = emalloc(len);
2544 BN_bn2bin(peer->iffval, vp->ptr);
2548 vp->sig = emalloc(sign_siglen);
2549 ctx = EVP_MD_CTX_new();
2550 EVP_SignInit(ctx, sign_digest);
2551 EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
2552 EVP_SignUpdate(ctx, vp->ptr, len);
2553 if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
2554 INSIST(len <= sign_siglen);
2555 vp->siglen = htonl(len);
2557 EVP_MD_CTX_free(ctx);
2563 * crypto_bob2 - construct Bob's response to Alice's challenge
2567 * XEVNT_ERR protocol error
2568 * XEVNT_ID bad or missing group key
2572 struct exten *ep, /* extension pointer */
2573 struct value *vp /* value pointer */
2576 RSA *rsa; /* GQ parameters */
2577 DSA_SIG *sdsa; /* DSA parameters */
2578 BN_CTX *bctx; /* BIGNUM context */
2579 EVP_MD_CTX *ctx; /* signature context */
2580 tstamp_t tstamp; /* NTP timestamp */
2581 BIGNUM *r, *k, *g, *y;
2585 const BIGNUM *n, *p, *e;
2588 * If the GQ parameters are not valid, something awful
2589 * happened or we are being tormented.
2591 if (gqkey_info == NULL) {
2592 msyslog(LOG_NOTICE, "crypto_bob2: scheme unavailable");
2595 rsa = EVP_PKEY_get0_RSA(gqkey_info->pkey);
2596 RSA_get0_key(rsa, &n, &p, &e);
2599 * Extract r from the challenge.
2601 len = exten_payload_size(ep);
2602 if (len == 0 || len > MAX_VALLEN)
2604 if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2605 msyslog(LOG_ERR, "crypto_bob2: %s",
2606 ERR_error_string(ERR_get_error(), NULL));
2611 * Bob rolls random k (0 < k < n), computes y = k u^r mod n and
2612 * x = k^b mod n, then sends (y, hash(x)) to Alice.
2614 bctx = BN_CTX_new(); k = BN_new(); g = BN_new(); y = BN_new();
2615 sdsa = DSA_SIG_new();
2616 BN_rand(k, len * 8, -1, 1); /* k */
2617 BN_mod(k, k, n, bctx);
2618 BN_mod_exp(y, p, r, n, bctx); /* u^r mod n */
2619 BN_mod_mul(y, k, y, n, bctx); /* k u^r mod n */
2620 BN_mod_exp(g, k, e, n, bctx); /* k^b mod n */
2622 DSA_SIG_set0(sdsa, y, g);
2624 BN_free(r); BN_free(k);
2627 RSA_print_fp(stdout, rsa, 0);
2631 * Encode the values in ASN.1 and sign. The filestamp is from
2634 len = s_len = i2d_DSA_SIG(sdsa, NULL);
2636 msyslog(LOG_ERR, "crypto_bob2: %s",
2637 ERR_error_string(ERR_get_error(), NULL));
2641 memset(vp, 0, sizeof(struct value));
2642 tstamp = crypto_time();
2643 vp->tstamp = htonl(tstamp);
2644 vp->fstamp = htonl(gqkey_info->fstamp);
2645 vp->vallen = htonl(len);
2648 i2d_DSA_SIG(sdsa, &ptr);
2653 vp->sig = emalloc(sign_siglen);
2654 ctx = EVP_MD_CTX_new();
2655 EVP_SignInit(ctx, sign_digest);
2656 EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
2657 EVP_SignUpdate(ctx, vp->ptr, len);
2658 if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
2659 INSIST(len <= sign_siglen);
2660 vp->siglen = htonl(len);
2662 EVP_MD_CTX_free(ctx);
2668 * crypto_gq - verify Bob's response to Alice's challenge
2672 * XEVNT_ERR protocol error
2673 * XEVNT_FSP bad filestamp
2674 * XEVNT_ID bad or missing group keys
2675 * XEVNT_PUB bad or missing public key
2679 struct exten *ep, /* extension pointer */
2680 struct peer *peer /* peer structure pointer */
2683 RSA *rsa; /* GQ parameters */
2684 BN_CTX *bctx; /* BIGNUM context */
2685 DSA_SIG *sdsa; /* RSA signature context fake */
2690 const BIGNUM *n, *e;
2691 const BIGNUM *r, *s;
2694 * If the GQ parameters are not valid or no challenge was sent,
2695 * something awful happened or we are being tormented. Note that
2696 * the filestamp on the local key file can be greater than on
2697 * the remote parameter file if the keys have been refreshed.
2699 if (peer->ident_pkey == NULL) {
2700 msyslog(LOG_NOTICE, "crypto_gq: scheme unavailable");
2703 if (ntohl(ep->fstamp) < peer->ident_pkey->fstamp) {
2704 msyslog(LOG_NOTICE, "crypto_gq: invalid filestamp %u",
2708 if ((rsa = EVP_PKEY_get0_RSA(peer->ident_pkey->pkey)) == NULL) {
2709 msyslog(LOG_NOTICE, "crypto_gq: defective key");
2712 RSA_get0_key(rsa, &n, NULL, &e);
2713 if (peer->iffval == NULL) {
2714 msyslog(LOG_NOTICE, "crypto_gq: missing challenge");
2719 * Extract the y = k u^r and hash(x = k^b) values from the
2722 bctx = BN_CTX_new(); y = BN_new(); v = BN_new();
2723 len = ntohl(ep->vallen);
2724 ptr = (u_char *)ep->pkt;
2725 if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2726 BN_CTX_free(bctx); BN_free(y); BN_free(v);
2727 msyslog(LOG_ERR, "crypto_gq: %s",
2728 ERR_error_string(ERR_get_error(), NULL));
2731 DSA_SIG_get0(sdsa, &r, &s);
2734 * Compute v^r y^b mod n.
2736 if (peer->grpkey == NULL) {
2737 msyslog(LOG_NOTICE, "crypto_gq: missing group key");
2740 BN_mod_exp(v, peer->grpkey, peer->iffval, n, bctx);
2742 BN_mod_exp(y, r, e, n, bctx); /* y^b mod n */
2743 BN_mod_mul(y, v, y, n, bctx); /* v^r y^b mod n */
2746 * Verify the hash of the result matches hash(x).
2749 temp = BN_cmp(y, s);
2750 BN_CTX_free(bctx); BN_free(y); BN_free(v);
2751 BN_free(peer->iffval);
2752 peer->iffval = NULL;
2757 msyslog(LOG_NOTICE, "crypto_gq: identity not verified");
2763 ***********************************************************************
2765 * The following routines implement the Mu-Varadharajan (MV) identity *
2768 ***********************************************************************
2770 * The Mu-Varadharajan (MV) cryptosystem was originally intended when
2771 * servers broadcast messages to clients, but clients never send
2772 * messages to servers. There is one encryption key for the server and a
2773 * separate decryption key for each client. It operated something like a
2774 * pay-per-view satellite broadcasting system where the session key is
2775 * encrypted by the broadcaster and the decryption keys are held in a
2776 * tamperproof set-top box.
2778 * The MV parameters and private encryption key hide in a DSA cuckoo
2779 * structure which uses the same parameters, but generated in a
2780 * different way. The values are used in an encryption scheme similar to
2781 * El Gamal cryptography and a polynomial formed from the expansion of
2782 * product terms (x - x[j]), as described in Mu, Y., and V.
2783 * Varadharajan: Robust and Secure Broadcasting, Proc. Indocrypt 2001,
2784 * 223-231. The paper has significant errors and serious omissions.
2786 * Let q be the product of n distinct primes s1[j] (j = 1...n), where
2787 * each s1[j] has m significant bits. Let p be a prime p = 2 * q + 1, so
2788 * that q and each s1[j] divide p - 1 and p has M = n * m + 1
2789 * significant bits. Let g be a generator of Zp; that is, gcd(g, p - 1)
2790 * = 1 and g^q = 1 mod p. We do modular arithmetic over Zq and then
2791 * project into Zp* as exponents of g. Sometimes we have to compute an
2792 * inverse b^-1 of random b in Zq, but for that purpose we require
2793 * gcd(b, q) = 1. We expect M to be in the 500-bit range and n
2794 * relatively small, like 30. These are the parameters of the scheme and
2795 * they are expensive to compute.
2797 * We set up an instance of the scheme as follows. A set of random
2798 * values x[j] mod q (j = 1...n), are generated as the zeros of a
2799 * polynomial of order n. The product terms (x - x[j]) are expanded to
2800 * form coefficients a[i] mod q (i = 0...n) in powers of x. These are
2801 * used as exponents of the generator g mod p to generate the private
2802 * encryption key A. The pair (gbar, ghat) of public server keys and the
2803 * pairs (xbar[j], xhat[j]) (j = 1...n) of private client keys are used
2804 * to construct the decryption keys. The devil is in the details.
2806 * This routine generates a private server encryption file including the
2807 * private encryption key E and partial decryption keys gbar and ghat.
2808 * It then generates public client decryption files including the public
2809 * keys xbar[j] and xhat[j] for each client j. The partial decryption
2810 * files are used to compute the inverse of E. These values are suitably
2811 * blinded so secrets are not revealed.
2813 * The distinguishing characteristic of this scheme is the capability to
2814 * revoke keys. Included in the calculation of E, gbar and ghat is the
2815 * product s = prod(s1[j]) (j = 1...n) above. If the factor s1[j] is
2816 * subsequently removed from the product and E, gbar and ghat
2817 * recomputed, the jth client will no longer be able to compute E^-1 and
2818 * thus unable to decrypt the messageblock.
2822 * The scheme goes like this. Bob has the server values (p, E, q, gbar,
2823 * ghat) and Alice has the client values (p, xbar, xhat).
2825 * Alice rolls new random nonce r mod p and sends to Bob in the MV
2826 * request message. Bob rolls random nonce k mod q, encrypts y = r E^k
2827 * mod p and sends (y, gbar^k, ghat^k) to Alice.
2829 * Alice receives the response and computes the inverse (E^k)^-1 from
2830 * the partial decryption keys gbar^k, ghat^k, xbar and xhat. She then
2831 * decrypts y and verifies it matches the original r. The signed
2832 * response binds this knowledge to Bob's private key and the public key
2833 * previously received in his certificate.
2835 * crypto_alice3 - construct Alice's challenge in MV scheme
2839 * XEVNT_ID bad or missing group key
2840 * XEVNT_PUB bad or missing public key
2844 struct peer *peer, /* peer pointer */
2845 struct value *vp /* value pointer */
2848 DSA *dsa; /* MV parameters */
2849 BN_CTX *bctx; /* BIGNUM context */
2850 EVP_MD_CTX *ctx; /* signature context */
2856 * The identity parameters must have correct format and content.
2858 if (peer->ident_pkey == NULL)
2861 if ((dsa = EVP_PKEY_get0_DSA(peer->ident_pkey->pkey)) == NULL) {
2862 msyslog(LOG_NOTICE, "crypto_alice3: defective key");
2865 DSA_get0_pqg(dsa, &p, NULL, NULL);
2868 * Roll new random r (0 < r < q).
2870 if (peer->iffval != NULL)
2871 BN_free(peer->iffval);
2872 peer->iffval = BN_new();
2873 len = BN_num_bytes(p);
2874 BN_rand(peer->iffval, len * 8, -1, 1); /* r mod p */
2875 bctx = BN_CTX_new();
2876 BN_mod(peer->iffval, peer->iffval, p, bctx);
2880 * Sign and send to Bob. The filestamp is from the local file.
2882 memset(vp, 0, sizeof(struct value));
2883 tstamp = crypto_time();
2884 vp->tstamp = htonl(tstamp);
2885 vp->fstamp = htonl(peer->ident_pkey->fstamp);
2886 vp->vallen = htonl(len);
2887 vp->ptr = emalloc(len);
2888 BN_bn2bin(peer->iffval, vp->ptr);
2892 vp->sig = emalloc(sign_siglen);
2893 ctx = EVP_MD_CTX_new();
2894 EVP_SignInit(ctx, sign_digest);
2895 EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
2896 EVP_SignUpdate(ctx, vp->ptr, len);
2897 if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
2898 INSIST(len <= sign_siglen);
2899 vp->siglen = htonl(len);
2901 EVP_MD_CTX_free(ctx);
2907 * crypto_bob3 - construct Bob's response to Alice's challenge
2911 * XEVNT_ERR protocol error
2915 struct exten *ep, /* extension pointer */
2916 struct value *vp /* value pointer */
2919 DSA *dsa; /* MV parameters */
2920 DSA *sdsa; /* DSA signature context fake */
2921 BN_CTX *bctx; /* BIGNUM context */
2922 EVP_MD_CTX *ctx; /* signature context */
2923 tstamp_t tstamp; /* NTP timestamp */
2927 const BIGNUM *p, *q, *g;
2928 const BIGNUM *pub_key, *priv_key;
2929 BIGNUM *sp, *sq, *sg;
2932 * If the MV parameters are not valid, something awful
2933 * happened or we are being tormented.
2935 if (mvkey_info == NULL) {
2936 msyslog(LOG_NOTICE, "crypto_bob3: scheme unavailable");
2939 dsa = EVP_PKEY_get0_DSA(mvkey_info->pkey);
2940 DSA_get0_pqg(dsa, &p, &q, &g);
2941 DSA_get0_key(dsa, &pub_key, &priv_key);
2944 * Extract r from the challenge.
2946 len = exten_payload_size(ep);
2947 if (len == 0 || len > MAX_VALLEN)
2949 if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2950 msyslog(LOG_ERR, "crypto_bob3: %s",
2951 ERR_error_string(ERR_get_error(), NULL));
2956 * Bob rolls random k (0 < k < q), making sure it is not a
2957 * factor of q. He then computes y = r A^k and sends (y, gbar^k,
2958 * and ghat^k) to Alice.
2960 bctx = BN_CTX_new(); k = BN_new(); u = BN_new();
2962 sp = BN_new(); sq = BN_new(); sg = BN_new();
2964 BN_rand(k, BN_num_bits(q), 0, 0);
2965 BN_mod(k, k, q, bctx);
2966 BN_gcd(u, k, q, bctx);
2970 BN_mod_exp(u, g, k, p, bctx); /* A^k r */
2971 BN_mod_mul(sp, u, r, p, bctx);
2972 BN_mod_exp(sq, priv_key, k, p, bctx); /* gbar */
2973 BN_mod_exp(sg, pub_key, k, p, bctx); /* ghat */
2974 DSA_set0_key(sdsa, BN_dup(pub_key), NULL);
2975 DSA_set0_pqg(sdsa, sp, sq, sg);
2976 BN_CTX_free(bctx); BN_free(k); BN_free(r); BN_free(u);
2979 DSA_print_fp(stdout, sdsa, 0);
2983 * Encode the values in ASN.1 and sign. The filestamp is from
2986 memset(vp, 0, sizeof(struct value));
2987 tstamp = crypto_time();
2988 vp->tstamp = htonl(tstamp);
2989 vp->fstamp = htonl(mvkey_info->fstamp);
2990 len = i2d_DSAparams(sdsa, NULL);
2992 msyslog(LOG_ERR, "crypto_bob3: %s",
2993 ERR_error_string(ERR_get_error(), NULL));
2997 vp->vallen = htonl(len);
3000 i2d_DSAparams(sdsa, &ptr);
3005 vp->sig = emalloc(sign_siglen);
3006 ctx = EVP_MD_CTX_new();
3007 EVP_SignInit(ctx, sign_digest);
3008 EVP_SignUpdate(ctx, (u_char *)&vp->tstamp, 12);
3009 EVP_SignUpdate(ctx, vp->ptr, len);
3010 if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
3011 INSIST(len <= sign_siglen);
3012 vp->siglen = htonl(len);
3014 EVP_MD_CTX_free(ctx);
3020 * crypto_mv - verify Bob's response to Alice's challenge
3024 * XEVNT_ERR protocol error
3025 * XEVNT_FSP bad filestamp
3026 * XEVNT_ID bad or missing group key
3027 * XEVNT_PUB bad or missing public key
3031 struct exten *ep, /* extension pointer */
3032 struct peer *peer /* peer structure pointer */
3035 DSA *dsa; /* MV parameters */
3036 DSA *sdsa; /* DSA parameters */
3037 BN_CTX *bctx; /* BIGNUM context */
3043 const BIGNUM *pub_key, *priv_key;
3044 const BIGNUM *sp, *sq, *sg;
3047 * If the MV parameters are not valid or no challenge was sent,
3048 * something awful happened or we are being tormented.
3050 if (peer->ident_pkey == NULL) {
3051 msyslog(LOG_NOTICE, "crypto_mv: scheme unavailable");
3054 if (ntohl(ep->fstamp) != peer->ident_pkey->fstamp) {
3055 msyslog(LOG_NOTICE, "crypto_mv: invalid filestamp %u",
3059 if ((dsa = EVP_PKEY_get0_DSA(peer->ident_pkey->pkey)) == NULL) {
3060 msyslog(LOG_NOTICE, "crypto_mv: defective key");
3063 DSA_get0_pqg(dsa, &p, NULL, NULL);
3064 DSA_get0_key(dsa, &pub_key, &priv_key);
3065 if (peer->iffval == NULL) {
3066 msyslog(LOG_NOTICE, "crypto_mv: missing challenge");
3071 * Extract the y, gbar and ghat values from the response.
3073 bctx = BN_CTX_new(); k = BN_new(); u = BN_new(); v = BN_new();
3074 len = ntohl(ep->vallen);
3075 ptr = (u_char *)ep->pkt;
3076 if ((sdsa = d2i_DSAparams(NULL, &ptr, len)) == NULL) {
3077 msyslog(LOG_ERR, "crypto_mv: %s",
3078 ERR_error_string(ERR_get_error(), NULL));
3081 DSA_get0_pqg(sdsa, &sp, &sq, &sg);
3084 * Compute (gbar^xhat ghat^xbar) mod p.
3086 BN_mod_exp(u, sq, pub_key, p, bctx);
3087 BN_mod_exp(v, sg, priv_key, p, bctx);
3088 BN_mod_mul(u, u, v, p, bctx);
3089 BN_mod_mul(u, u, sp, p, bctx);
3092 * The result should match r.
3094 temp = BN_cmp(u, peer->iffval);
3095 BN_CTX_free(bctx); BN_free(k); BN_free(u); BN_free(v);
3096 BN_free(peer->iffval);
3097 peer->iffval = NULL;
3102 msyslog(LOG_NOTICE, "crypto_mv: identity not verified");
3108 ***********************************************************************
3110 * The following routines are used to manipulate certificates *
3112 ***********************************************************************
3115 * cert_sign - sign x509 certificate equest and update value structure.
3117 * The certificate request includes a copy of the host certificate,
3118 * which includes the version number, subject name and public key of the
3119 * host. The resulting certificate includes these values plus the
3120 * serial number, issuer name and valid interval of the server. The
3121 * valid interval extends from the current time to the same time one
3122 * year hence. This may extend the life of the signed certificate beyond
3123 * that of the signer certificate.
3125 * It is convenient to use the NTP seconds of the current time as the
3126 * serial number. In the value structure the timestamp is the current
3127 * time and the filestamp is taken from the extension field. Note this
3128 * routine is called only when the client clock is synchronized to a
3129 * proventic source, so timestamp comparisons are valid.
3131 * The host certificate is valid from the time it was generated for a
3132 * period of one year. A signed certificate is valid from the time of
3133 * signature for a period of one year, but only the host certificate (or
3134 * sign certificate if used) is actually used to encrypt and decrypt
3135 * signatures. The signature trail is built from the client via the
3136 * intermediate servers to the trusted server. Each signature on the
3137 * trail must be valid at the time of signature, but it could happen
3138 * that a signer certificate expire before the signed certificate, which
3139 * remains valid until its expiration.
3143 * XEVNT_CRT bad or missing certificate
3144 * XEVNT_PER host certificate expired
3145 * XEVNT_PUB bad or missing public key
3146 * XEVNT_VFY certificate not verified
3150 struct exten *ep, /* extension field pointer */
3151 struct value *vp /* value pointer */
3154 X509 *req; /* X509 certificate request */
3155 X509 *cert; /* X509 certificate */
3156 X509_EXTENSION *ext; /* certificate extension */
3157 ASN1_INTEGER *serial; /* serial number */
3158 X509_NAME *subj; /* distinguished (common) name */
3159 EVP_PKEY *pkey; /* public key */
3160 EVP_MD_CTX *ctx; /* message digest context */
3161 tstamp_t tstamp; /* NTP timestamp */
3162 struct calendar tscal;
3169 * Decode ASN.1 objects and construct certificate structure.
3170 * Make sure the system clock is synchronized to a proventic
3173 tstamp = crypto_time();
3177 len = exten_payload_size(ep);
3178 if (len == 0 || len > MAX_VALLEN)
3180 cptr = (void *)ep->pkt;
3181 if ((req = d2i_X509(NULL, &cptr, len)) == NULL) {
3182 msyslog(LOG_ERR, "cert_sign: %s",
3183 ERR_error_string(ERR_get_error(), NULL));
3187 * Extract public key and check for errors.
3189 if ((pkey = X509_get_pubkey(req)) == NULL) {
3190 msyslog(LOG_ERR, "cert_sign: %s",
3191 ERR_error_string(ERR_get_error(), NULL));
3197 * Generate X509 certificate signed by this server. If this is a
3198 * trusted host, the issuer name is the group name; otherwise,
3199 * it is the host name. Also copy any extensions that might be
3203 X509_set_version(cert, X509_get_version(req));
3204 serial = ASN1_INTEGER_new();
3205 ASN1_INTEGER_set(serial, tstamp);
3206 X509_set_serialNumber(cert, serial);
3207 X509_gmtime_adj(X509_getm_notBefore(cert), 0L);
3208 X509_gmtime_adj(X509_getm_notAfter(cert), YEAR);
3209 subj = X509_get_issuer_name(cert);
3210 X509_NAME_add_entry_by_txt(subj, "commonName", MBSTRING_ASC,
3211 hostval.ptr, strlen((const char *)hostval.ptr), -1, 0);
3212 subj = X509_get_subject_name(req);
3213 X509_set_subject_name(cert, subj);
3214 X509_set_pubkey(cert, pkey);
3215 temp = X509_get_ext_count(req);
3216 for (i = 0; i < temp; i++) {
3217 ext = X509_get_ext(req, i);
3218 INSIST(X509_add_ext(cert, ext, -1));
3223 * Sign and verify the client certificate, but only if the host
3224 * certificate has not expired.
3226 (void)ntpcal_ntp_to_date(&tscal, tstamp, NULL);
3227 if ((calcomp(&tscal, &(cert_host->first)) < 0)
3228 || (calcomp(&tscal, &(cert_host->last)) > 0)) {
3232 X509_sign(cert, sign_pkey, sign_digest);
3233 if (X509_verify(cert, sign_pkey) <= 0) {
3234 msyslog(LOG_ERR, "cert_sign: %s",
3235 ERR_error_string(ERR_get_error(), NULL));
3239 len = i2d_X509(cert, NULL);
3242 * Build and sign the value structure. We have to sign it here,
3243 * since the response has to be returned right away. This is a
3246 memset(vp, 0, sizeof(struct value));
3247 vp->tstamp = htonl(tstamp);
3248 vp->fstamp = ep->fstamp;
3249 vp->vallen = htonl(len);
3250 vp->ptr = emalloc(len);
3252 i2d_X509(cert, (unsigned char **)(intptr_t)&ptr);
3255 vp->sig = emalloc(sign_siglen);
3256 ctx = EVP_MD_CTX_new();
3257 EVP_SignInit(ctx, sign_digest);
3258 EVP_SignUpdate(ctx, (u_char *)vp, 12);
3259 EVP_SignUpdate(ctx, vp->ptr, len);
3260 if (EVP_SignFinal(ctx, vp->sig, &len, sign_pkey)) {
3261 INSIST(len <= sign_siglen);
3262 vp->siglen = htonl(len);
3264 EVP_MD_CTX_free(ctx);
3268 X509_print_fp(stdout, cert);
3276 * cert_install - install certificate in certificate cache
3278 * This routine encodes an extension field into a certificate info/value
3279 * structure. It searches the certificate list for duplicates and
3280 * expunges whichever is older. Finally, it inserts this certificate
3281 * first on the list.
3283 * Returns certificate info pointer if valid, NULL if not.
3287 struct exten *ep, /* cert info/value */
3288 struct peer *peer /* peer structure */
3291 struct cert_info *cp, *xp, **zp;
3294 * Parse and validate the signed certificate. If valid,
3295 * construct the info/value structure; otherwise, scamper home
3298 if ((cp = cert_parse((u_char *)ep->pkt, (long)ntohl(ep->vallen),
3299 (tstamp_t)ntohl(ep->fstamp))) == NULL)
3303 * Scan certificate list looking for another certificate with
3304 * the same subject and issuer. If another is found with the
3305 * same or older filestamp, unlink it and return the goodies to
3306 * the heap. If another is found with a later filestamp, discard
3307 * the new one and leave the building with the old one.
3309 * Make a note to study this issue again. An earlier certificate
3310 * with a long lifetime might be overtaken by a later
3311 * certificate with a short lifetime, thus invalidating the
3312 * earlier signature. However, we gotta find a way to leak old
3313 * stuff from the cache, so we do it anyway.
3316 for (xp = cinfo; xp != NULL; xp = xp->link) {
3317 if (strcmp(cp->subject, xp->subject) == 0 &&
3318 strcmp(cp->issuer, xp->issuer) == 0) {
3319 if (ntohl(cp->cert.fstamp) <=
3320 ntohl(xp->cert.fstamp)) {
3336 cp->flags |= CERT_VALID;
3343 * cert_hike - verify the signature using the issuer public key
3347 * XEVNT_CRT bad or missing certificate
3348 * XEVNT_PER host certificate expired
3349 * XEVNT_VFY certificate not verified
3353 struct peer *peer, /* peer structure pointer */
3354 struct cert_info *yp /* issuer certificate */
3357 struct cert_info *xp; /* subject certificate */
3358 X509 *cert; /* X509 certificate */
3362 * Save the issuer on the new certificate, but remember the old
3365 if (peer->issuer != NULL)
3367 peer->issuer = estrdup(yp->issuer);
3372 * If subject Y matches issuer Y, then the certificate trail is
3373 * complete. If Y is not trusted, the server certificate has yet
3374 * been signed, so keep trying. Otherwise, save the group key
3375 * and light the valid bit. If the host certificate is trusted,
3376 * do not execute a sign exchange. If no identity scheme is in
3377 * use, light the identity and proventic bits.
3379 if (strcmp(yp->subject, yp->issuer) == 0) {
3380 if (!(yp->flags & CERT_TRUST))
3384 * If the server has an an identity scheme, fetch the
3385 * identity credentials. If not, the identity is
3386 * verified only by the trusted certificate. The next
3387 * signature will set the server proventic.
3389 peer->crypto |= CRYPTO_FLAG_CERT;
3390 peer->grpkey = yp->grpkey;
3391 if (peer->ident == NULL || !(peer->crypto &
3393 peer->crypto |= CRYPTO_FLAG_VRFY;
3397 * If X exists, verify signature X using public key Y.
3402 ptr = (u_char *)xp->cert.ptr;
3403 cert = d2i_X509(NULL, &ptr, ntohl(xp->cert.vallen));
3405 xp->flags |= CERT_ERROR;
3408 if (X509_verify(cert, yp->pkey) <= 0) {
3410 xp->flags |= CERT_ERROR;
3416 * Signature X is valid only if it begins during the
3419 if ((calcomp(&(xp->first), &(yp->first)) < 0)
3420 || (calcomp(&(xp->first), &(yp->last)) > 0)) {
3421 xp->flags |= CERT_ERROR;
3424 xp->flags |= CERT_SIGN;
3430 * cert_parse - parse x509 certificate and create info/value structures.
3432 * The server certificate includes the version number, issuer name,
3433 * subject name, public key and valid date interval. If the issuer name
3434 * is the same as the subject name, the certificate is self signed and
3435 * valid only if the server is configured as trustable. If the names are
3436 * different, another issuer has signed the server certificate and
3437 * vouched for it. In this case the server certificate is valid if
3438 * verified by the issuer public key.
3440 * Returns certificate info/value pointer if valid, NULL if not.
3442 struct cert_info * /* certificate information structure */
3444 const u_char *asn1cert, /* X509 certificate */
3445 long len, /* certificate length */
3446 tstamp_t fstamp /* filestamp */
3449 X509 *cert; /* X509 certificate */
3450 struct cert_info *ret; /* certificate info/value */
3452 char pathbuf[MAXFILENAME];
3456 struct calendar fscal;
3459 * Decode ASN.1 objects and construct certificate structure.
3462 if ((cert = d2i_X509(NULL, &ptr, len)) == NULL) {
3463 msyslog(LOG_ERR, "cert_parse: %s",
3464 ERR_error_string(ERR_get_error(), NULL));
3469 X509_print_fp(stdout, cert);
3473 * Extract version, subject name and public key.
3475 ret = emalloc_zero(sizeof(*ret));
3476 if ((ret->pkey = X509_get_pubkey(cert)) == NULL) {
3477 msyslog(LOG_ERR, "cert_parse: %s",
3478 ERR_error_string(ERR_get_error(), NULL));
3483 ret->version = X509_get_version(cert);
3484 X509_NAME_oneline(X509_get_subject_name(cert), pathbuf,
3486 pch = strstr(pathbuf, "CN=");
3488 msyslog(LOG_NOTICE, "cert_parse: invalid subject %s",
3494 ret->subject = estrdup(pch + 3);
3497 * Extract remaining objects. Note that the NTP serial number is
3498 * the NTP seconds at the time of signing, but this might not be
3499 * the case for other authority. We don't bother to check the
3500 * objects at this time, since the real crunch can happen only
3501 * when the time is valid but not yet certificated.
3503 ret->nid = X509_get_signature_nid(cert);
3504 ret->digest = (const EVP_MD *)EVP_get_digestbynid(ret->nid);
3506 (u_long)ASN1_INTEGER_get(X509_get_serialNumber(cert));
3507 X509_NAME_oneline(X509_get_issuer_name(cert), pathbuf,
3509 if ((pch = strstr(pathbuf, "CN=")) == NULL) {
3510 msyslog(LOG_NOTICE, "cert_parse: invalid issuer %s",
3516 ret->issuer = estrdup(pch + 3);
3517 asn_to_calendar(X509_get0_notBefore(cert), &(ret->first));
3518 asn_to_calendar(X509_get0_notAfter(cert), &(ret->last));
3521 * Extract extension fields. These are ad hoc ripoffs of
3522 * currently assigned functions and will certainly be changed
3523 * before prime time.
3525 cnt = X509_get_ext_count(cert);
3526 for (i = 0; i < cnt; i++) {
3527 X509_EXTENSION *ext;
3530 ASN1_OCTET_STRING *data;
3532 ext = X509_get_ext(cert, i);
3533 obj = X509_EXTENSION_get_object(ext);
3534 nid = OBJ_obj2nid(obj);
3539 * If a key_usage field is present, we decode whether
3540 * this is a trusted or private certificate. This is
3541 * dorky; all we want is to compare NIDs, but OpenSSL
3542 * insists on BIO text strings.
3544 case NID_ext_key_usage:
3545 bp = BIO_new(BIO_s_mem());
3546 X509V3_EXT_print(bp, ext, 0, 0);
3547 BIO_gets(bp, pathbuf, sizeof(pathbuf));
3549 if (strcmp(pathbuf, "Trust Root") == 0)
3550 ret->flags |= CERT_TRUST;
3551 else if (strcmp(pathbuf, "Private") == 0)
3552 ret->flags |= CERT_PRIV;
3553 DPRINTF(1, ("cert_parse: %s: %s\n",
3554 OBJ_nid2ln(nid), pathbuf));
3558 * If a NID_subject_key_identifier field is present, it
3559 * contains the GQ public key.
3561 case NID_subject_key_identifier:
3562 data = X509_EXTENSION_get_data(ext);
3563 ret->grpkey = BN_bin2bn(&data->data[2],
3564 data->length - 2, NULL);
3567 DPRINTF(1, ("cert_parse: %s\n",
3572 if (strcmp(ret->subject, ret->issuer) == 0) {
3575 * If certificate is self signed, verify signature.
3577 if (X509_verify(cert, ret->pkey) <= 0) {
3579 "cert_parse: signature not verified %s",
3588 * Check for a certificate loop.
3590 if (strcmp((const char *)hostval.ptr, ret->issuer) == 0) {
3592 "cert_parse: certificate trail loop %s",
3601 * Verify certificate valid times. Note that certificates cannot
3604 (void)ntpcal_ntp_to_date(&fscal, fstamp, NULL);
3605 if ((calcomp(&(ret->first), &(ret->last)) > 0)
3606 || (calcomp(&(ret->first), &fscal) < 0)) {
3608 "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",
3610 ret->first.year, ret->first.month, ret->first.monthday,
3611 ret->first.hour, ret->first.minute, ret->first.second,
3612 ret->last.year, ret->last.month, ret->last.monthday,
3613 ret->last.hour, ret->last.minute, ret->last.second,
3614 fscal.year, fscal.month, fscal.monthday,
3615 fscal.hour, fscal.minute, fscal.second);
3622 * Build the value structure to sign and send later.
3624 ret->cert.fstamp = htonl(fstamp);
3625 ret->cert.vallen = htonl(len);
3626 ret->cert.ptr = emalloc(len);
3627 memcpy(ret->cert.ptr, asn1cert, len);
3634 * cert_free - free certificate information structure
3638 struct cert_info *cinf /* certificate info/value structure */
3641 if (cinf->pkey != NULL)
3642 EVP_PKEY_free(cinf->pkey);
3643 if (cinf->subject != NULL)
3644 free(cinf->subject);
3645 if (cinf->issuer != NULL)
3647 if (cinf->grpkey != NULL)
3648 BN_free(cinf->grpkey);
3649 value_free(&cinf->cert);
3655 * crypto_key - load cryptographic parameters and keys
3657 * This routine searches the key cache for matching name in the form
3658 * ntpkey_<key>_<name>, where <key> is one of host, sign, iff, gq, mv,
3659 * and <name> is the host/group name. If not found, it tries to load a
3660 * PEM-encoded file of the same name and extracts the filestamp from
3661 * the first line of the file name. It returns the key pointer if valid,
3664 static struct pkey_info *
3666 char *cp, /* file name */
3667 char *passwd1, /* password */
3668 sockaddr_u *addr /* IP address */
3671 FILE *str; /* file handle */
3672 struct pkey_info *pkp; /* generic key */
3673 EVP_PKEY *pkey = NULL; /* public/private key */
3675 char filename[MAXFILENAME]; /* name of key file */
3676 char linkname[MAXFILENAME]; /* filestamp buffer) */
3677 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3681 * Search the key cache for matching key and name.
3683 for (pkp = pkinfo; pkp != NULL; pkp = pkp->link) {
3684 if (strcmp(cp, pkp->name) == 0)
3689 * Open the key file. If the first character of the file name is
3690 * not '/', prepend the keys directory string. If something goes
3691 * wrong, abandon ship.
3694 strlcpy(filename, cp, sizeof(filename));
3696 snprintf(filename, sizeof(filename), "%s/%s", keysdir,
3698 str = fopen(filename, "r");
3703 * Read the filestamp, which is contained in the first line.
3705 if ((ptr = fgets(linkname, sizeof(linkname), str)) == NULL) {
3706 msyslog(LOG_ERR, "crypto_key: empty file %s",
3711 if ((ptr = strrchr(ptr, '.')) == NULL) {
3712 msyslog(LOG_ERR, "crypto_key: no filestamp %s",
3717 if (sscanf(++ptr, "%u", &fstamp) != 1) {
3718 msyslog(LOG_ERR, "crypto_key: invalid filestamp %s",
3725 * Read and decrypt PEM-encoded private key. If it fails to
3726 * decrypt, game over.
3728 pkey = PEM_read_PrivateKey(str, NULL, NULL, passwd1);
3731 msyslog(LOG_ERR, "crypto_key: %s",
3732 ERR_error_string(ERR_get_error(), NULL));
3737 * Make a new entry in the key cache.
3739 pkp = emalloc(sizeof(struct pkey_info));
3743 pkp->name = estrdup(cp);
3744 pkp->fstamp = fstamp;
3747 * Leave tracks in the cryptostats.
3749 if ((ptr = strrchr(linkname, '\n')) != NULL)
3751 snprintf(statstr, sizeof(statstr), "%s mod %d", &linkname[2],
3752 EVP_PKEY_size(pkey) * 8);
3753 record_crypto_stats(addr, statstr);
3755 DPRINTF(1, ("crypto_key: %s\n", statstr));
3758 if (EVP_PKEY_base_id(pkey) == EVP_PKEY_DSA)
3759 DSA_print_fp(stdout, EVP_PKEY_get0_DSA(pkey), 0);
3760 else if (EVP_PKEY_base_id(pkey) == EVP_PKEY_RSA)
3761 RSA_print_fp(stdout, EVP_PKEY_get0_RSA(pkey), 0);
3769 ***********************************************************************
3771 * The following routines are used only at initialization time *
3773 ***********************************************************************
3776 * crypto_cert - load certificate from file
3778 * This routine loads an X.509 RSA or DSA certificate from a file and
3779 * constructs a info/cert value structure for this machine. The
3780 * structure includes a filestamp extracted from the file name. Later
3781 * the certificate can be sent to another machine on request.
3783 * Returns certificate info/value pointer if valid, NULL if not.
3785 static struct cert_info * /* certificate information */
3787 char *cp /* file name */
3790 struct cert_info *ret; /* certificate information */
3791 FILE *str; /* file handle */
3792 char filename[MAXFILENAME]; /* name of certificate file */
3793 char linkname[MAXFILENAME]; /* filestamp buffer */
3794 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3795 tstamp_t fstamp; /* filestamp */
3798 char *name, *header;
3802 * Open the certificate file. If the first character of the file
3803 * name is not '/', prepend the keys directory string. If
3804 * something goes wrong, abandon ship.
3807 strlcpy(filename, cp, sizeof(filename));
3809 snprintf(filename, sizeof(filename), "%s/%s", keysdir,
3811 str = fopen(filename, "r");
3816 * Read the filestamp, which is contained in the first line.
3818 if ((ptr = fgets(linkname, sizeof(linkname), str)) == NULL) {
3819 msyslog(LOG_ERR, "crypto_cert: empty file %s",
3824 if ((ptr = strrchr(ptr, '.')) == NULL) {
3825 msyslog(LOG_ERR, "crypto_cert: no filestamp %s",
3830 if (sscanf(++ptr, "%u", &fstamp) != 1) {
3831 msyslog(LOG_ERR, "crypto_cert: invalid filestamp %s",
3838 * Read PEM-encoded certificate and install.
3840 if (!PEM_read(str, &name, &header, &data, &len)) {
3841 msyslog(LOG_ERR, "crypto_cert: %s",
3842 ERR_error_string(ERR_get_error(), NULL));
3848 if (strcmp(name, "CERTIFICATE") != 0) {
3849 msyslog(LOG_NOTICE, "crypto_cert: wrong PEM type %s",
3858 * Parse certificate and generate info/value structure. The
3859 * pointer and copy nonsense is due something broken in Solaris.
3861 ret = cert_parse(data, len, fstamp);
3866 if ((ptr = strrchr(linkname, '\n')) != NULL)
3868 snprintf(statstr, sizeof(statstr), "%s 0x%x len %lu",
3869 &linkname[2], ret->flags, len);
3870 record_crypto_stats(NULL, statstr);
3871 DPRINTF(1, ("crypto_cert: %s\n", statstr));
3877 * crypto_setup - load keys, certificate and identity parameters
3879 * This routine loads the public/private host key and certificate. If
3880 * available, it loads the public/private sign key, which defaults to
3881 * the host key. The host key must be RSA, but the sign key can be
3882 * either RSA or DSA. If a trusted certificate, it loads the identity
3883 * parameters. In either case, the public key on the certificate must
3884 * agree with the sign key.
3886 * Required but missing files and inconsistent data and errors are
3887 * fatal. Allowing configuration to continue would be hazardous and
3888 * require really messy error checks.
3893 struct pkey_info *pinfo; /* private/public key */
3894 char filename[MAXFILENAME]; /* file name buffer */
3895 char hostname[MAXFILENAME]; /* host name buffer */
3897 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3898 l_fp seed; /* crypto PRNG seed as NTP timestamp */
3904 * Check for correct OpenSSL version and avoid initialization in
3905 * the case of multiple crypto commands.
3907 if (crypto_flags & CRYPTO_FLAG_ENAB) {
3909 "crypto_setup: spurious crypto command");
3912 ssl_check_version();
3915 * Load required random seed file and seed the random number
3916 * generator. Be default, it is found as .rnd in the user home
3917 * directory. The root home directory may be / or /root,
3918 * depending on the system. Wiggle the contents a bit and write
3919 * it back so the sequence does not repeat when we next restart.
3921 if (!RAND_status()) {
3922 if (rand_file == NULL) {
3923 RAND_file_name(filename, sizeof(filename));
3924 randfile = filename;
3925 } else if (*rand_file != '/') {
3926 snprintf(filename, sizeof(filename), "%s/%s",
3927 keysdir, rand_file);
3928 randfile = filename;
3930 randfile = rand_file;
3932 if ((bytes = RAND_load_file(randfile, -1)) == 0) {
3934 "crypto_setup: random seed file %s missing",
3938 arc4random_buf(&seed, sizeof(l_fp));
3939 RAND_seed(&seed, sizeof(l_fp));
3940 RAND_write_file(randfile);
3941 DPRINTF(1, ("crypto_setup: OpenSSL version %lx random seed file %s bytes read %d\n",
3942 OpenSSL_version_num(), randfile, bytes));
3947 * Initialize structures.
3949 gethostname(hostname, sizeof(hostname));
3950 if (host_filename != NULL)
3951 strlcpy(hostname, host_filename, sizeof(hostname));
3953 passwd = estrdup(hostname);
3954 memset(&hostval, 0, sizeof(hostval));
3955 memset(&pubkey, 0, sizeof(pubkey));
3956 memset(&tai_leap, 0, sizeof(tai_leap));
3959 * Load required host key from file "ntpkey_host_<hostname>". If
3960 * no host key file is not found or has invalid password, life
3961 * as we know it ends. The host key also becomes the default
3964 snprintf(filename, sizeof(filename), "ntpkey_host_%s", hostname);
3965 pinfo = crypto_key(filename, passwd, NULL);
3966 if (pinfo == NULL) {
3968 "crypto_setup: host key file %s not found or corrupt",
3972 if (EVP_PKEY_base_id(pinfo->pkey) != EVP_PKEY_RSA) {
3974 "crypto_setup: host key is not RSA key type");
3977 host_pkey = pinfo->pkey;
3978 sign_pkey = host_pkey;
3979 hostval.fstamp = htonl(pinfo->fstamp);
3982 * Construct public key extension field for agreement scheme.
3984 len = i2d_PublicKey(host_pkey, NULL);
3987 i2d_PublicKey(host_pkey, &ptr);
3988 pubkey.fstamp = hostval.fstamp;
3989 pubkey.vallen = htonl(len);
3992 * Load optional sign key from file "ntpkey_sign_<hostname>". If
3993 * available, it becomes the sign key.
3995 snprintf(filename, sizeof(filename), "ntpkey_sign_%s", hostname);
3996 pinfo = crypto_key(filename, passwd, NULL);
3998 sign_pkey = pinfo->pkey;
4001 * Load required certificate from file "ntpkey_cert_<hostname>".
4003 snprintf(filename, sizeof(filename), "ntpkey_cert_%s", hostname);
4004 cinfo = crypto_cert(filename);
4005 if (cinfo == NULL) {
4007 "crypto_setup: certificate file %s not found or corrupt",
4012 sign_digest = cinfo->digest;
4013 sign_siglen = EVP_PKEY_size(sign_pkey);
4014 if (cinfo->flags & CERT_PRIV)
4015 crypto_flags |= CRYPTO_FLAG_PRIV;
4018 * The certificate must be self-signed.
4020 if (strcmp(cinfo->subject, cinfo->issuer) != 0) {
4022 "crypto_setup: certificate %s is not self-signed",
4026 hostval.ptr = estrdup(cinfo->subject);
4027 hostval.vallen = htonl(strlen(cinfo->subject));
4028 sys_hostname = hostval.ptr;
4029 ptr = (u_char *)strchr(sys_hostname, '@');
4031 sys_groupname = estrdup((char *)++ptr);
4032 if (ident_filename != NULL)
4033 strlcpy(hostname, ident_filename, sizeof(hostname));
4036 * Load optional IFF parameters from file
4037 * "ntpkey_iffkey_<hostname>".
4039 snprintf(filename, sizeof(filename), "ntpkey_iffkey_%s",
4041 iffkey_info = crypto_key(filename, passwd, NULL);
4042 if (iffkey_info != NULL)
4043 crypto_flags |= CRYPTO_FLAG_IFF;
4046 * Load optional GQ parameters from file
4047 * "ntpkey_gqkey_<hostname>".
4049 snprintf(filename, sizeof(filename), "ntpkey_gqkey_%s",
4051 gqkey_info = crypto_key(filename, passwd, NULL);
4052 if (gqkey_info != NULL)
4053 crypto_flags |= CRYPTO_FLAG_GQ;
4056 * Load optional MV parameters from file
4057 * "ntpkey_mvkey_<hostname>".
4059 snprintf(filename, sizeof(filename), "ntpkey_mvkey_%s",
4061 mvkey_info = crypto_key(filename, passwd, NULL);
4062 if (mvkey_info != NULL)
4063 crypto_flags |= CRYPTO_FLAG_MV;
4066 * We met the enemy and he is us. Now strike up the dance.
4068 crypto_flags |= CRYPTO_FLAG_ENAB | (cinfo->nid << 16);
4069 snprintf(statstr, sizeof(statstr), "setup 0x%x host %s %s",
4070 crypto_flags, hostname, OBJ_nid2ln(cinfo->nid));
4071 record_crypto_stats(NULL, statstr);
4072 DPRINTF(1, ("crypto_setup: %s\n", statstr));
4077 * crypto_config - configure data from the crypto command.
4081 int item, /* configuration item */
4082 char *cp /* item name */
4087 DPRINTF(1, ("crypto_config: item %d %s\n", item, cp));
4092 * Set host name (host).
4094 case CRYPTO_CONF_PRIV:
4095 if (NULL != host_filename)
4096 free(host_filename);
4097 host_filename = estrdup(cp);
4101 * Set group name (ident).
4103 case CRYPTO_CONF_IDENT:
4104 if (NULL != ident_filename)
4105 free(ident_filename);
4106 ident_filename = estrdup(cp);
4110 * Set private key password (pw).
4112 case CRYPTO_CONF_PW:
4115 passwd = estrdup(cp);
4119 * Set random seed file name (randfile).
4121 case CRYPTO_CONF_RAND:
4122 if (NULL != rand_file)
4124 rand_file = estrdup(cp);
4128 * Set message digest NID.
4130 case CRYPTO_CONF_NID:
4131 nid = OBJ_sn2nid(cp);
4134 "crypto_config: invalid digest name %s", cp);
4142 * Get the payload size (internal value length) of an extension packet.
4143 * If the inner value size does not match the outer packet size (that
4144 * is, the value would end behind the frame given by the opcode/size
4145 * field) the function will effectively return UINT_MAX. If the frame is
4146 * too short to hold a variable-sized value, the return value is zero.
4150 const struct exten * ep)
4152 typedef const u_char *BPTR;
4160 head_size = (BPTR)(&ep->vallen + 1) - (BPTR)ep;
4161 extn_size = (uint16_t)(ntohl(ep->opcode) & 0x0000ffff);
4162 if (extn_size >= head_size) {
4163 data_size = (uint32_t)ntohl(ep->vallen);
4164 if (data_size > extn_size - head_size)
4165 data_size = ~(size_t)0u;
4168 return (u_int)data_size;
4170 # else /* !AUTOKEY follows */
4171 int ntp_crypto_bs_pubkey;
4172 # endif /* !AUTOKEY */