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_mac.h"
26 #include "openssl/bn.h"
27 #include "openssl/err.h"
28 #include "openssl/evp.h"
29 #include "openssl/pem.h"
30 #include "openssl/rand.h"
31 #include "openssl/x509v3.h"
34 #include "ntp_syscall.h"
35 #endif /* KERNEL_PLL */
38 * calcomp - compare two calendar structures, ignoring yearday and weekday; like strcmp
39 * No, it's not a plotter. If you don't understand that, you're too young.
41 static int calcomp(struct calendar *pjd1, struct calendar *pjd2)
43 int32_t diff; /* large enough to hold the signed difference between two uint16_t values */
45 diff = pjd1->year - pjd2->year;
46 if (diff < 0) return -1; else if (diff > 0) return 1;
47 /* same year; compare months */
48 diff = pjd1->month - pjd2->month;
49 if (diff < 0) return -1; else if (diff > 0) return 1;
50 /* same year and month; compare monthday */
51 diff = pjd1->monthday - pjd2->monthday;
52 if (diff < 0) return -1; else if (diff > 0) return 1;
53 /* same year and month and monthday; compare time */
54 diff = pjd1->hour - pjd2->hour;
55 if (diff < 0) return -1; else if (diff > 0) return 1;
56 diff = pjd1->minute - pjd2->minute;
57 if (diff < 0) return -1; else if (diff > 0) return 1;
58 diff = pjd1->second - pjd2->second;
59 if (diff < 0) return -1; else if (diff > 0) return 1;
65 * Extension field message format
67 * These are always signed and saved before sending in network byte
68 * order. They must be converted to and from host byte order for
72 * | op | len | <- extension pointer
76 * | timestamp | <- value pointer
93 * The CRYPTO_RESP bit is set to 0 for requests, 1 for responses.
94 * Requests carry the association ID of the receiver; responses carry
95 * the association ID of the sender. Some messages include only the
96 * operation/length and association ID words and so have length 8
97 * octets. Ohers include the value structure and associated value and
98 * signature fields. These messages include the timestamp, filestamp,
99 * value and signature words and so have length at least 24 octets. The
100 * signature and/or value fields can be empty, in which case the
101 * respective length words are zero. An empty value with nonempty
102 * signature is syntactically valid, but semantically questionable.
104 * The filestamp represents the time when a cryptographic data file such
105 * as a public/private key pair is created. It follows every reference
106 * depending on that file and serves as a means to obsolete earlier data
107 * of the same type. The timestamp represents the time when the
108 * cryptographic data of the message were last signed. Creation of a
109 * cryptographic data file or signing a message can occur only when the
110 * creator or signor is synchronized to an authoritative source and
111 * proventicated to a trusted authority.
113 * Note there are several conditions required for server trust. First,
114 * the public key on the server certificate must be verified, which can
115 * involve a hike along the certificate trail to a trusted host. Next,
116 * the server trust must be confirmed by one of several identity
117 * schemes. Valid cryptographic values are signed with attached
118 * timestamp and filestamp. Individual packet trust is confirmed
119 * relative to these values by a message digest with keys generated by a
120 * reverse-order pseudorandom hash.
122 * State decomposition. These flags are lit in the order given. They are
123 * dim only when the association is demobilized.
125 * CRYPTO_FLAG_ENAB Lit upon acceptance of a CRYPTO_ASSOC message
126 * CRYPTO_FLAG_CERT Lit when a self-digned trusted certificate is
128 * CRYPTO_FLAG_VRFY Lit when identity is confirmed.
129 * CRYPTO_FLAG_PROV Lit when the first signature is verified.
130 * CRYPTO_FLAG_COOK Lit when a valid cookie is accepted.
131 * CRYPTO_FLAG_AUTO Lit when valid autokey values are accepted.
132 * CRYPTO_FLAG_SIGN Lit when the server signed certificate is
134 * CRYPTO_FLAG_LEAP Lit when the leapsecond values are accepted.
139 #define TAI_1972 10 /* initial TAI offset (s) */
140 #define MAX_LEAP 100 /* max UTC leapseconds (s) */
141 #define VALUE_LEN (6 * 4) /* min response field length */
142 #define MAX_VALLEN (65535 - VALUE_LEN)
143 #define YEAR (60 * 60 * 24 * 365) /* seconds in year */
146 * Global cryptodata in host byte order
148 u_int32 crypto_flags = 0x0; /* status word */
149 int crypto_nid = KEY_TYPE_MD5; /* digest nid */
150 char *sys_hostname = NULL;
151 char *sys_groupname = NULL;
152 static char *host_filename = NULL; /* host file name */
153 static char *ident_filename = NULL; /* group file name */
156 * Global cryptodata in network byte order
158 struct cert_info *cinfo = NULL; /* certificate info/value cache */
159 struct cert_info *cert_host = NULL; /* host certificate */
160 struct pkey_info *pkinfo = NULL; /* key info/value cache */
161 struct value hostval; /* host value */
162 struct value pubkey; /* public key */
163 struct value tai_leap; /* leapseconds values */
164 struct pkey_info *iffkey_info = NULL; /* IFF keys */
165 struct pkey_info *gqkey_info = NULL; /* GQ keys */
166 struct pkey_info *mvkey_info = NULL; /* MV keys */
169 * Private cryptodata in host byte order
171 static char *passwd = NULL; /* private key password */
172 static EVP_PKEY *host_pkey = NULL; /* host key */
173 static EVP_PKEY *sign_pkey = NULL; /* sign key */
174 static const EVP_MD *sign_digest = NULL; /* sign digest */
175 static u_int sign_siglen; /* sign key length */
176 static char *rand_file = NULL; /* random seed file */
181 static int crypto_verify (struct exten *, struct value *,
183 static int crypto_encrypt (const u_char *, u_int, keyid_t *,
185 static int crypto_alice (struct peer *, struct value *);
186 static int crypto_alice2 (struct peer *, struct value *);
187 static int crypto_alice3 (struct peer *, struct value *);
188 static int crypto_bob (struct exten *, struct value *);
189 static int crypto_bob2 (struct exten *, struct value *);
190 static int crypto_bob3 (struct exten *, struct value *);
191 static int crypto_iff (struct exten *, struct peer *);
192 static int crypto_gq (struct exten *, struct peer *);
193 static int crypto_mv (struct exten *, struct peer *);
194 static int crypto_send (struct exten *, struct value *, int);
195 static tstamp_t crypto_time (void);
196 static void asn_to_calendar (ASN1_TIME *, struct calendar*);
197 static struct cert_info *cert_parse (const u_char *, long, tstamp_t);
198 static int cert_sign (struct exten *, struct value *);
199 static struct cert_info *cert_install (struct exten *, struct peer *);
200 static int cert_hike (struct peer *, struct cert_info *);
201 static void cert_free (struct cert_info *);
202 static struct pkey_info *crypto_key (char *, char *, sockaddr_u *);
203 static void bighash (BIGNUM *, BIGNUM *);
204 static struct cert_info *crypto_cert (char *);
205 static u_int exten_payload_size(const struct exten *);
209 readlink(char * link, char * file, int len) {
215 * session_key - generate session key
217 * This routine generates a session key from the source address,
218 * destination address, key ID and private value. The value of the
219 * session key is the MD5 hash of these values, while the next key ID is
220 * the first four octets of the hash.
222 * Returns the next key ID or 0 if there is no destination address.
226 sockaddr_u *srcadr, /* source address */
227 sockaddr_u *dstadr, /* destination address */
228 keyid_t keyno, /* key ID */
229 keyid_t private, /* private value */
230 u_long lifetime /* key lifetime */
233 EVP_MD_CTX ctx; /* message digest context */
234 u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
235 keyid_t keyid; /* key identifer */
236 u_int32 header[10]; /* data in network byte order */
243 * Generate the session key and key ID. If the lifetime is
244 * greater than zero, install the key and call it trusted.
249 header[0] = NSRCADR(srcadr);
250 header[1] = NSRCADR(dstadr);
251 header[2] = htonl(keyno);
252 header[3] = htonl(private);
253 hdlen = 4 * sizeof(u_int32);
257 memcpy(&header[0], PSOCK_ADDR6(srcadr),
258 sizeof(struct in6_addr));
259 memcpy(&header[4], PSOCK_ADDR6(dstadr),
260 sizeof(struct in6_addr));
261 header[8] = htonl(keyno);
262 header[9] = htonl(private);
263 hdlen = 10 * sizeof(u_int32);
266 EVP_DigestInit(&ctx, EVP_get_digestbynid(crypto_nid));
267 EVP_DigestUpdate(&ctx, (u_char *)header, hdlen);
268 EVP_DigestFinal(&ctx, dgst, &len);
269 memcpy(&keyid, dgst, 4);
270 keyid = ntohl(keyid);
272 MD5auth_setkey(keyno, crypto_nid, dgst, len);
273 authtrust(keyno, lifetime);
275 DPRINTF(2, ("session_key: %s > %s %08x %08x hash %08x life %lu\n",
276 stoa(srcadr), stoa(dstadr), keyno,
277 private, keyid, lifetime));
284 * make_keylist - generate key list
288 * XEVNT_ERR protocol error
290 * This routine constructs a pseudo-random sequence by repeatedly
291 * hashing the session key starting from a given source address,
292 * destination address, private value and the next key ID of the
293 * preceeding session key. The last entry on the list is saved along
294 * with its sequence number and public signature.
298 struct peer *peer, /* peer structure pointer */
299 struct interface *dstadr /* interface */
302 EVP_MD_CTX ctx; /* signature context */
303 tstamp_t tstamp; /* NTP timestamp */
304 struct autokey *ap; /* autokey pointer */
305 struct value *vp; /* value pointer */
306 keyid_t keyid = 0; /* next key ID */
307 keyid_t cookie; /* private value */
316 * Allocate the key list if necessary.
318 tstamp = crypto_time();
319 if (peer->keylist == NULL)
320 peer->keylist = eallocarray(NTP_MAXSESSION,
324 * Generate an initial key ID which is unique and greater than
328 keyid = ntp_random() & 0xffffffff;
329 if (keyid <= NTP_MAXKEY)
332 if (authhavekey(keyid))
338 * Generate up to NTP_MAXSESSION session keys. Stop if the
339 * next one would not be unique or not a session key ID or if
340 * it would expire before the next poll. The private value
341 * included in the hash is zero if broadcast mode, the peer
342 * cookie if client mode or the host cookie if symmetric modes.
344 mpoll = 1 << min(peer->ppoll, peer->hpoll);
345 lifetime = min(1U << sys_automax, NTP_MAXSESSION * mpoll);
346 if (peer->hmode == MODE_BROADCAST)
349 cookie = peer->pcookie;
350 for (i = 0; i < NTP_MAXSESSION; i++) {
351 peer->keylist[i] = keyid;
353 keyid = session_key(&dstadr->sin, &peer->srcadr, keyid,
354 cookie, lifetime + mpoll);
356 if (auth_havekey(keyid) || keyid <= NTP_MAXKEY ||
357 lifetime < 0 || tstamp == 0)
362 * Save the last session key ID, sequence number and timestamp,
363 * then sign these values for later retrieval by the clients. Be
364 * careful not to use invalid key media. Use the public values
365 * timestamp as filestamp.
369 vp->ptr = emalloc(sizeof(struct autokey));
370 ap = (struct autokey *)vp->ptr;
371 ap->seq = htonl(peer->keynumber);
372 ap->key = htonl(keyid);
373 vp->tstamp = htonl(tstamp);
374 vp->fstamp = hostval.tstamp;
375 vp->vallen = htonl(sizeof(struct autokey));
379 vp->sig = emalloc(sign_siglen);
380 EVP_SignInit(&ctx, sign_digest);
381 EVP_SignUpdate(&ctx, (u_char *)vp, 12);
382 EVP_SignUpdate(&ctx, vp->ptr, sizeof(struct autokey));
383 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
384 INSIST(len <= sign_siglen);
385 vp->siglen = htonl(len);
386 peer->flags |= FLAG_ASSOC;
389 DPRINTF(1, ("make_keys: %d %08x %08x ts %u fs %u poll %d\n",
390 peer->keynumber, keyid, cookie, ntohl(vp->tstamp),
391 ntohl(vp->fstamp), peer->hpoll));
397 * crypto_recv - parse extension fields
399 * This routine is called when the packet has been matched to an
400 * association and passed sanity, format and MAC checks. We believe the
401 * extension field values only if the field has proper format and
402 * length, the timestamp and filestamp are valid and the signature has
403 * valid length and is verified. There are a few cases where some values
404 * are believed even if the signature fails, but only if the proventic
409 * XEVNT_ERR protocol error
410 * XEVNT_LEN bad field format or length
414 struct peer *peer, /* peer structure pointer */
415 struct recvbuf *rbufp /* packet buffer pointer */
418 const EVP_MD *dp; /* message digest algorithm */
419 u_int32 *pkt; /* receive packet pointer */
420 struct autokey *ap, *bp; /* autokey pointer */
421 struct exten *ep, *fp; /* extension pointers */
422 struct cert_info *xinfo; /* certificate info pointer */
423 int macbytes; /* length of MAC field, signed by intention */
424 int authlen; /* offset of MAC field */
425 associd_t associd; /* association ID */
426 tstamp_t fstamp = 0; /* filestamp */
427 u_int len; /* extension field length */
428 u_int code; /* extension field opcode */
429 u_int vallen = 0; /* value length */
430 X509 *cert; /* X509 certificate */
431 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
432 keyid_t cookie; /* crumbles */
433 int hismode; /* packet mode */
439 * Initialize. Note that the packet has already been checked for
440 * valid format and extension field lengths. First extract the
441 * field length, command code and association ID in host byte
442 * order. These are used with all commands and modes. Then check
443 * the version number, which must be 2, and length, which must
444 * be at least 8 for requests and VALUE_LEN (24) for responses.
445 * Packets that fail either test sink without a trace. The
446 * association ID is saved only if nonzero.
448 authlen = LEN_PKT_NOMAC;
449 hismode = (int)PKT_MODE((&rbufp->recv_pkt)->li_vn_mode);
450 while ((macbytes = rbufp->recv_length - authlen) > (int)MAX_MAC_LEN) {
451 /* We can be reasonably sure that we can read at least
452 * the opcode and the size field here. More stringent
453 * checks follow up shortly.
455 pkt = (u_int32 *)&rbufp->recv_pkt + authlen / 4;
456 ep = (struct exten *)pkt;
457 code = ntohl(ep->opcode) & 0xffff0000;
458 len = ntohl(ep->opcode) & 0x0000ffff;
459 // HMS: Why pkt[1] instead of ep->associd ?
460 associd = (associd_t)ntohl(pkt[1]);
462 DPRINTF(1, ("crypto_recv: flags 0x%x ext offset %d len %u code 0x%x associd %d\n",
463 peer->crypto, authlen, len, code >> 16,
467 * Check version number and field length. If bad,
468 * quietly ignore the packet.
470 if (((code >> 24) & 0x3f) != CRYPTO_VN || len < 8) {
472 code |= CRYPTO_ERROR;
475 /* Check if the declared size fits into the remaining
476 * buffer. We *know* 'macbytes' > 0 here!
478 if (len > (u_int)macbytes) {
479 DPRINTF(1, ("crypto_recv: possible attack detected, associd %d\n",
484 /* Check if the paylod of the extension fits into the
487 if (len >= VALUE_LEN) {
488 fstamp = ntohl(ep->fstamp);
489 vallen = ntohl(ep->vallen);
491 * Bug 2761: I hope this isn't too early...
494 || len - VALUE_LEN < vallen)
500 * Install status word, host name, signature scheme and
501 * association ID. In OpenSSL the signature algorithm is
502 * bound to the digest algorithm, so the NID completely
503 * defines the signature scheme. Note the request and
504 * response are identical, but neither is validated by
505 * signature. The request is processed here only in
506 * symmetric modes. The server name field might be
507 * useful to implement access controls in future.
512 * If our state machine is running when this
513 * message arrives, the other fellow might have
514 * restarted. However, this could be an
515 * intruder, so just clamp the poll interval and
516 * find out for ourselves. Otherwise, pass the
517 * extension field to the transmit side.
519 if (peer->crypto & CRYPTO_FLAG_CERT) {
524 if (peer->assoc != associd) {
528 free(peer->cmmd); /* will be set again! */
532 fp->associd = htonl(peer->associd);
536 case CRYPTO_ASSOC | CRYPTO_RESP:
539 * Discard the message if it has already been
540 * stored or the message has been amputated.
543 if (peer->assoc != associd)
547 INSIST(len >= VALUE_LEN);
548 if (vallen == 0 || vallen > MAXHOSTNAME ||
549 len - VALUE_LEN < vallen) {
553 DPRINTF(1, ("crypto_recv: ident host 0x%x %d server 0x%x %d\n",
554 crypto_flags, peer->associd, fstamp,
556 temp32 = crypto_flags & CRYPTO_FLAG_MASK;
559 * If the client scheme is PC, the server scheme
560 * must be PC. The public key and identity are
561 * presumed valid, so we skip the certificate
562 * and identity exchanges and move immediately
563 * to the cookie exchange which confirms the
566 if (crypto_flags & CRYPTO_FLAG_PRIV) {
567 if (!(fstamp & CRYPTO_FLAG_PRIV)) {
571 fstamp |= CRYPTO_FLAG_CERT |
572 CRYPTO_FLAG_VRFY | CRYPTO_FLAG_SIGN;
575 * It is an error if either peer supports
576 * identity, but the other does not.
578 } else if (hismode == MODE_ACTIVE || hismode ==
580 if ((temp32 && !(fstamp &
581 CRYPTO_FLAG_MASK)) ||
582 (!temp32 && (fstamp &
583 CRYPTO_FLAG_MASK))) {
590 * Discard the message if the signature digest
591 * NID is not supported.
593 temp32 = (fstamp >> 16) & 0xffff;
595 (const EVP_MD *)EVP_get_digestbynid(temp32);
602 * Save status word, host name and message
603 * digest/signature type. If this is from a
604 * broadcast and the association ID has changed,
605 * request the autokey values.
607 peer->assoc = associd;
608 if (hismode == MODE_SERVER)
609 fstamp |= CRYPTO_FLAG_AUTO;
610 if (!(fstamp & CRYPTO_FLAG_TAI))
611 fstamp |= CRYPTO_FLAG_LEAP;
612 RAND_bytes((u_char *)&peer->hcookie, 4);
613 peer->crypto = fstamp;
615 if (peer->subject != NULL)
617 peer->subject = emalloc(vallen + 1);
618 memcpy(peer->subject, ep->pkt, vallen);
619 peer->subject[vallen] = '\0';
620 if (peer->issuer != NULL)
622 peer->issuer = estrdup(peer->subject);
623 snprintf(statstr, sizeof(statstr),
624 "assoc %d %d host %s %s", peer->associd,
625 peer->assoc, peer->subject,
627 record_crypto_stats(&peer->srcadr, statstr);
628 DPRINTF(1, ("crypto_recv: %s\n", statstr));
632 * Decode X509 certificate in ASN.1 format and extract
633 * the data containing, among other things, subject
634 * name and public key. In the default identification
635 * scheme, the certificate trail is followed to a self
636 * signed trusted certificate.
638 case CRYPTO_CERT | CRYPTO_RESP:
641 * Discard the message if empty or invalid.
646 if ((rval = crypto_verify(ep, NULL, peer)) !=
651 * Scan the certificate list to delete old
652 * versions and link the newest version first on
653 * the list. Then, verify the signature. If the
654 * certificate is bad or missing, just ignore
657 if ((xinfo = cert_install(ep, peer)) == NULL) {
661 if ((rval = cert_hike(peer, xinfo)) != XEVNT_OK)
665 * We plug in the public key and lifetime from
666 * the first certificate received. However, note
667 * that this certificate might not be signed by
668 * the server, so we can't check the
669 * signature/digest NID.
671 if (peer->pkey == NULL) {
672 puch = xinfo->cert.ptr;
673 cert = d2i_X509(NULL, &puch,
674 ntohl(xinfo->cert.vallen));
675 peer->pkey = X509_get_pubkey(cert);
678 peer->flash &= ~TEST8;
680 snprintf(statstr, sizeof(statstr),
681 "cert %s %s 0x%x %s (%u) fs %u",
682 xinfo->subject, xinfo->issuer, xinfo->flags,
683 OBJ_nid2ln(temp32), temp32,
685 record_crypto_stats(&peer->srcadr, statstr);
686 DPRINTF(1, ("crypto_recv: %s\n", statstr));
690 * Schnorr (IFF) identity scheme. This scheme is
691 * designed for use with shared secret server group keys
692 * and where the certificate may be generated by a third
693 * party. The client sends a challenge to the server,
694 * which performs a calculation and returns the result.
695 * A positive result is possible only if both client and
696 * server contain the same secret group key.
698 case CRYPTO_IFF | CRYPTO_RESP:
701 * Discard the message if invalid.
703 if ((rval = crypto_verify(ep, NULL, peer)) !=
708 * If the challenge matches the response, the
709 * server public key, signature and identity are
710 * all verified at the same time. The server is
711 * declared trusted, so we skip further
712 * certificate exchanges and move immediately to
713 * the cookie exchange.
715 if ((rval = crypto_iff(ep, peer)) != XEVNT_OK)
718 peer->crypto |= CRYPTO_FLAG_VRFY;
719 peer->flash &= ~TEST8;
720 snprintf(statstr, sizeof(statstr), "iff %s fs %u",
721 peer->issuer, ntohl(ep->fstamp));
722 record_crypto_stats(&peer->srcadr, statstr);
723 DPRINTF(1, ("crypto_recv: %s\n", statstr));
727 * Guillou-Quisquater (GQ) identity scheme. This scheme
728 * is designed for use with public certificates carrying
729 * the GQ public key in an extension field. The client
730 * sends a challenge to the server, which performs a
731 * calculation and returns the result. A positive result
732 * is possible only if both client and server contain
733 * the same group key and the server has the matching GQ
736 case CRYPTO_GQ | CRYPTO_RESP:
739 * Discard the message if invalid
741 if ((rval = crypto_verify(ep, NULL, peer)) !=
746 * If the challenge matches the response, the
747 * server public key, signature and identity are
748 * all verified at the same time. The server is
749 * declared trusted, so we skip further
750 * certificate exchanges and move immediately to
751 * the cookie exchange.
753 if ((rval = crypto_gq(ep, peer)) != XEVNT_OK)
756 peer->crypto |= CRYPTO_FLAG_VRFY;
757 peer->flash &= ~TEST8;
758 snprintf(statstr, sizeof(statstr), "gq %s fs %u",
759 peer->issuer, ntohl(ep->fstamp));
760 record_crypto_stats(&peer->srcadr, statstr);
761 DPRINTF(1, ("crypto_recv: %s\n", statstr));
765 * Mu-Varadharajan (MV) identity scheme. This scheme is
766 * designed for use with three levels of trust, trusted
767 * host, server and client. The trusted host key is
768 * opaque to servers and clients; the server keys are
769 * opaque to clients and each client key is different.
770 * Client keys can be revoked without requiring new key
773 case CRYPTO_MV | CRYPTO_RESP:
776 * Discard the message if invalid.
778 if ((rval = crypto_verify(ep, NULL, peer)) !=
783 * If the challenge matches the response, the
784 * server public key, signature and identity are
785 * all verified at the same time. The server is
786 * declared trusted, so we skip further
787 * certificate exchanges and move immediately to
788 * the cookie exchange.
790 if ((rval = crypto_mv(ep, peer)) != XEVNT_OK)
793 peer->crypto |= CRYPTO_FLAG_VRFY;
794 peer->flash &= ~TEST8;
795 snprintf(statstr, sizeof(statstr), "mv %s fs %u",
796 peer->issuer, ntohl(ep->fstamp));
797 record_crypto_stats(&peer->srcadr, statstr);
798 DPRINTF(1, ("crypto_recv: %s\n", statstr));
803 * Cookie response in client and symmetric modes. If the
804 * cookie bit is set, the working cookie is the EXOR of
805 * the current and new values.
807 case CRYPTO_COOK | CRYPTO_RESP:
810 * Discard the message if invalid or signature
811 * not verified with respect to the cookie
814 if ((rval = crypto_verify(ep, &peer->cookval,
819 * Decrypt the cookie, hunting all the time for
822 if (vallen == (u_int)EVP_PKEY_size(host_pkey)) {
823 u_int32 *cookiebuf = malloc(
824 RSA_size(host_pkey->pkey.rsa));
830 if (RSA_private_decrypt(vallen,
834 RSA_PKCS1_OAEP_PADDING) != 4) {
839 cookie = ntohl(*cookiebuf);
848 * Install cookie values and light the cookie
849 * bit. If this is not broadcast client mode, we
853 if (hismode == MODE_ACTIVE || hismode ==
855 peer->pcookie = peer->hcookie ^ cookie;
857 peer->pcookie = cookie;
858 peer->crypto |= CRYPTO_FLAG_COOK;
859 peer->flash &= ~TEST8;
860 snprintf(statstr, sizeof(statstr),
861 "cook %x ts %u fs %u", peer->pcookie,
862 ntohl(ep->tstamp), ntohl(ep->fstamp));
863 record_crypto_stats(&peer->srcadr, statstr);
864 DPRINTF(1, ("crypto_recv: %s\n", statstr));
868 * Install autokey values in broadcast client and
869 * symmetric modes. We have to do this every time the
870 * sever/peer cookie changes or a new keylist is
871 * rolled. Ordinarily, this is automatic as this message
872 * is piggybacked on the first NTP packet sent upon
873 * either of these events. Note that a broadcast client
874 * or symmetric peer can receive this response without a
877 case CRYPTO_AUTO | CRYPTO_RESP:
880 * Discard the message if invalid or signature
881 * not verified with respect to the receive
884 if ((rval = crypto_verify(ep, &peer->recval,
889 * Discard the message if a broadcast client and
890 * the association ID does not match. This might
891 * happen if a broacast server restarts the
892 * protocol. A protocol restart will occur at
893 * the next ASSOC message.
895 if ((peer->cast_flags & MDF_BCLNT) &&
896 peer->assoc != associd)
900 * Install autokey values and light the
901 * autokey bit. This is not hard.
906 if (peer->recval.ptr == NULL)
908 emalloc(sizeof(struct autokey));
909 bp = (struct autokey *)peer->recval.ptr;
910 peer->recval.tstamp = ep->tstamp;
911 peer->recval.fstamp = ep->fstamp;
912 ap = (struct autokey *)ep->pkt;
913 bp->seq = ntohl(ap->seq);
914 bp->key = ntohl(ap->key);
915 peer->pkeyid = bp->key;
916 peer->crypto |= CRYPTO_FLAG_AUTO;
917 peer->flash &= ~TEST8;
918 snprintf(statstr, sizeof(statstr),
919 "auto seq %d key %x ts %u fs %u", bp->seq,
920 bp->key, ntohl(ep->tstamp),
922 record_crypto_stats(&peer->srcadr, statstr);
923 DPRINTF(1, ("crypto_recv: %s\n", statstr));
927 * X509 certificate sign response. Validate the
928 * certificate signed by the server and install. Later
929 * this can be provided to clients of this server in
930 * lieu of the self signed certificate in order to
931 * validate the public key.
933 case CRYPTO_SIGN | CRYPTO_RESP:
936 * Discard the message if invalid.
938 if ((rval = crypto_verify(ep, NULL, peer)) !=
943 * Scan the certificate list to delete old
944 * versions and link the newest version first on
947 if ((xinfo = cert_install(ep, peer)) == NULL) {
951 peer->crypto |= CRYPTO_FLAG_SIGN;
952 peer->flash &= ~TEST8;
954 snprintf(statstr, sizeof(statstr),
955 "sign %s %s 0x%x %s (%u) fs %u",
956 xinfo->subject, xinfo->issuer, xinfo->flags,
957 OBJ_nid2ln(temp32), temp32,
959 record_crypto_stats(&peer->srcadr, statstr);
960 DPRINTF(1, ("crypto_recv: %s\n", statstr));
964 * Install leapseconds values. While the leapsecond
965 * values epoch, TAI offset and values expiration epoch
966 * are retained, only the current TAI offset is provided
967 * via the kernel to other applications.
969 case CRYPTO_LEAP | CRYPTO_RESP:
971 * Discard the message if invalid. We can't
972 * compare the value timestamps here, as they
973 * can be updated by different servers.
975 rval = crypto_verify(ep, NULL, peer);
976 if ((rval != XEVNT_OK ) ||
977 (vallen != 3*sizeof(uint32_t)) )
980 /* Check if we can update the basic TAI offset
981 * for our current leap frame. This is a hack
982 * and ignores the time stamps in the autokey
985 if (sys_leap != LEAP_NOTINSYNC)
986 leapsec_autokey_tai(ntohl(ep->pkt[0]),
987 rbufp->recv_time.l_ui, NULL);
988 tai_leap.tstamp = ep->tstamp;
989 tai_leap.fstamp = ep->fstamp;
991 mprintf_event(EVNT_TAI, peer,
992 "%d seconds", ntohl(ep->pkt[0]));
993 peer->crypto |= CRYPTO_FLAG_LEAP;
994 peer->flash &= ~TEST8;
995 snprintf(statstr, sizeof(statstr),
996 "leap TAI offset %d at %u expire %u fs %u",
997 ntohl(ep->pkt[0]), ntohl(ep->pkt[1]),
998 ntohl(ep->pkt[2]), ntohl(ep->fstamp));
999 record_crypto_stats(&peer->srcadr, statstr);
1000 DPRINTF(1, ("crypto_recv: %s\n", statstr));
1004 * We come here in symmetric modes for miscellaneous
1005 * commands that have value fields but are processed on
1006 * the transmit side. All we need do here is check for
1007 * valid field length. Note that ASSOC is handled
1016 if (len < VALUE_LEN) {
1023 * We come here in symmetric modes for requests
1024 * requiring a response (above plus AUTO and LEAP) and
1025 * for responses. If a request, save the extension field
1026 * for later; invalid requests will be caught on the
1027 * transmit side. If an error or invalid response,
1028 * declare a protocol error.
1031 if (code & (CRYPTO_RESP | CRYPTO_ERROR)) {
1033 } else if (peer->cmmd == NULL) {
1035 memcpy(fp, ep, len);
1041 * The first error found terminates the extension field
1042 * scan and we return the laundry to the caller.
1044 if (rval != XEVNT_OK) {
1045 snprintf(statstr, sizeof(statstr),
1046 "%04x %d %02x %s", htonl(ep->opcode),
1047 associd, rval, eventstr(rval));
1048 record_crypto_stats(&peer->srcadr, statstr);
1049 DPRINTF(1, ("crypto_recv: %s\n", statstr));
1052 authlen += (len + 3) / 4 * 4;
1059 * crypto_xmit - construct extension fields
1061 * This routine is called both when an association is configured and
1062 * when one is not. The only case where this matters is to retrieve the
1063 * autokey information, in which case the caller has to provide the
1064 * association ID to match the association.
1066 * Side effect: update the packet offset.
1070 * XEVNT_CRT bad or missing certificate
1071 * XEVNT_ERR protocol error
1072 * XEVNT_LEN bad field format or length
1073 * XEVNT_PER host certificate expired
1077 struct peer *peer, /* peer structure pointer */
1078 struct pkt *xpkt, /* transmit packet pointer */
1079 struct recvbuf *rbufp, /* receive buffer pointer */
1080 int start, /* offset to extension field */
1081 struct exten *ep, /* extension pointer */
1082 keyid_t cookie /* session cookie */
1085 struct exten *fp; /* extension pointers */
1086 struct cert_info *cp, *xp, *yp; /* cert info/value pointer */
1087 sockaddr_u *srcadr_sin; /* source address */
1088 u_int32 *pkt; /* packet pointer */
1089 u_int opcode; /* extension field opcode */
1090 char certname[MAXHOSTNAME + 1]; /* subject name buffer */
1091 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1093 struct calendar tscal;
1102 * Generate the requested extension field request code, length
1103 * and association ID. If this is a response and the host is not
1104 * synchronized, light the error bit and go home.
1106 pkt = (u_int32 *)xpkt + start / 4;
1107 fp = (struct exten *)pkt;
1108 opcode = ntohl(ep->opcode);
1110 srcadr_sin = &peer->srcadr;
1111 if (!(opcode & CRYPTO_RESP))
1112 peer->opcode = ep->opcode;
1114 srcadr_sin = &rbufp->recv_srcadr;
1116 associd = (associd_t) ntohl(ep->associd);
1118 fp->opcode = htonl((opcode & 0xffff0000) | len);
1119 fp->associd = ep->associd;
1121 tstamp = crypto_time();
1122 switch (opcode & 0xffff0000) {
1125 * Send association request and response with status word and
1126 * host name. Note, this message is not signed and the filestamp
1127 * contains only the status word.
1130 case CRYPTO_ASSOC | CRYPTO_RESP:
1131 len = crypto_send(fp, &hostval, start);
1132 fp->fstamp = htonl(crypto_flags);
1136 * Send certificate request. Use the values from the extension
1140 memset(&vtemp, 0, sizeof(vtemp));
1141 vtemp.tstamp = ep->tstamp;
1142 vtemp.fstamp = ep->fstamp;
1143 vtemp.vallen = ep->vallen;
1144 vtemp.ptr = (u_char *)ep->pkt;
1145 len = crypto_send(fp, &vtemp, start);
1149 * Send sign request. Use the host certificate, which is self-
1150 * signed and may or may not be trusted.
1153 (void)ntpcal_ntp_to_date(&tscal, tstamp, NULL);
1154 if ((calcomp(&tscal, &(cert_host->first)) < 0)
1155 || (calcomp(&tscal, &(cert_host->last)) > 0))
1158 len = crypto_send(fp, &cert_host->cert, start);
1162 * Send certificate response. Use the name in the extension
1163 * field to find the certificate in the cache. If the request
1164 * contains no subject name, assume the name of this host. This
1165 * is for backwards compatibility. Private certificates are
1168 * There may be several certificates matching the request. First
1169 * choice is a self-signed trusted certificate; second choice is
1170 * any certificate signed by another host. There is no third
1173 case CRYPTO_CERT | CRYPTO_RESP:
1174 vallen = exten_payload_size(ep); /* Must be <64k */
1175 if (vallen == 0 || vallen >= sizeof(certname) ) {
1181 * Find all public valid certificates with matching
1182 * subject. If a self-signed, trusted certificate is
1183 * found, use that certificate. If not, use the last non
1184 * self-signed certificate.
1186 memcpy(certname, ep->pkt, vallen);
1187 certname[vallen] = '\0';
1189 for (cp = cinfo; cp != NULL; cp = cp->link) {
1190 if (cp->flags & (CERT_PRIV | CERT_ERROR))
1193 if (strcmp(certname, cp->subject) != 0)
1196 if (strcmp(certname, cp->issuer) != 0)
1198 else if (cp ->flags & CERT_TRUST)
1204 * Be careful who you trust. If the certificate is not
1205 * found, return an empty response. Note that we dont
1206 * enforce lifetimes here.
1208 * The timestamp and filestamp are taken from the
1209 * certificate value structure. For all certificates the
1210 * timestamp is the latest signature update time. For
1211 * host and imported certificates the filestamp is the
1212 * creation epoch. For signed certificates the filestamp
1213 * is the creation epoch of the trusted certificate at
1214 * the root of the certificate trail. In principle, this
1215 * allows strong checking for signature masquerade.
1225 len = crypto_send(fp, &xp->cert, start);
1229 * Send challenge in Schnorr (IFF) identity scheme.
1233 break; /* hack attack */
1235 if ((rval = crypto_alice(peer, &vtemp)) == XEVNT_OK) {
1236 len = crypto_send(fp, &vtemp, start);
1242 * Send response in Schnorr (IFF) identity scheme.
1244 case CRYPTO_IFF | CRYPTO_RESP:
1245 if ((rval = crypto_bob(ep, &vtemp)) == XEVNT_OK) {
1246 len = crypto_send(fp, &vtemp, start);
1252 * Send challenge in Guillou-Quisquater (GQ) identity scheme.
1256 break; /* hack attack */
1258 if ((rval = crypto_alice2(peer, &vtemp)) == XEVNT_OK) {
1259 len = crypto_send(fp, &vtemp, start);
1265 * Send response in Guillou-Quisquater (GQ) identity scheme.
1267 case CRYPTO_GQ | CRYPTO_RESP:
1268 if ((rval = crypto_bob2(ep, &vtemp)) == XEVNT_OK) {
1269 len = crypto_send(fp, &vtemp, start);
1275 * Send challenge in MV identity scheme.
1279 break; /* hack attack */
1281 if ((rval = crypto_alice3(peer, &vtemp)) == XEVNT_OK) {
1282 len = crypto_send(fp, &vtemp, start);
1288 * Send response in MV identity scheme.
1290 case CRYPTO_MV | CRYPTO_RESP:
1291 if ((rval = crypto_bob3(ep, &vtemp)) == XEVNT_OK) {
1292 len = crypto_send(fp, &vtemp, start);
1298 * Send certificate sign response. The integrity of the request
1299 * certificate has already been verified on the receive side.
1300 * Sign the response using the local server key. Use the
1301 * filestamp from the request and use the timestamp as the
1302 * current time. Light the error bit if the certificate is
1303 * invalid or contains an unverified signature.
1305 case CRYPTO_SIGN | CRYPTO_RESP:
1306 if ((rval = cert_sign(ep, &vtemp)) == XEVNT_OK) {
1307 len = crypto_send(fp, &vtemp, start);
1313 * Send public key and signature. Use the values from the public
1317 len = crypto_send(fp, &pubkey, start);
1321 * Encrypt and send cookie and signature. Light the error bit if
1322 * anything goes wrong.
1324 case CRYPTO_COOK | CRYPTO_RESP:
1325 vallen = ntohl(ep->vallen); /* Must be <64k */
1327 || (vallen >= MAX_VALLEN)
1328 || (opcode & 0x0000ffff) < VALUE_LEN + vallen) {
1335 tcookie = peer->hcookie;
1336 if ((rval = crypto_encrypt((const u_char *)ep->pkt, vallen, &tcookie, &vtemp))
1338 len = crypto_send(fp, &vtemp, start);
1344 * Find peer and send autokey data and signature in broadcast
1345 * server and symmetric modes. Use the values in the autokey
1346 * structure. If no association is found, either the server has
1347 * restarted with new associations or some perp has replayed an
1348 * old message, in which case light the error bit.
1350 case CRYPTO_AUTO | CRYPTO_RESP:
1352 if ((peer = findpeerbyassoc(associd)) == NULL) {
1357 peer->flags &= ~FLAG_ASSOC;
1358 len = crypto_send(fp, &peer->sndval, start);
1362 * Send leapseconds values and signature. Use the values from
1363 * the tai structure. If no table has been loaded, just send an
1366 case CRYPTO_LEAP | CRYPTO_RESP:
1367 len = crypto_send(fp, &tai_leap, start);
1371 * Default - Send a valid command for unknown requests; send
1372 * an error response for unknown resonses.
1375 if (opcode & CRYPTO_RESP)
1380 * In case of error, flame the log. If a request, toss the
1381 * puppy; if a response, return so the sender can flame, too.
1383 if (rval != XEVNT_OK) {
1386 uint32 = CRYPTO_ERROR;
1388 fp->opcode |= htonl(uint32);
1389 snprintf(statstr, sizeof(statstr),
1390 "%04x %d %02x %s", opcode, associd, rval,
1392 record_crypto_stats(srcadr_sin, statstr);
1393 DPRINTF(1, ("crypto_xmit: %s\n", statstr));
1394 if (!(opcode & CRYPTO_RESP))
1397 DPRINTF(1, ("crypto_xmit: flags 0x%x offset %d len %d code 0x%x associd %d\n",
1398 crypto_flags, start, len, opcode >> 16, associd));
1404 * crypto_verify - verify the extension field value and signature
1408 * XEVNT_ERR protocol error
1409 * XEVNT_FSP bad filestamp
1410 * XEVNT_LEN bad field format or length
1411 * XEVNT_PUB bad or missing public key
1412 * XEVNT_SGL bad signature length
1413 * XEVNT_SIG signature not verified
1414 * XEVNT_TSP bad timestamp
1418 struct exten *ep, /* extension pointer */
1419 struct value *vp, /* value pointer */
1420 struct peer *peer /* peer structure pointer */
1423 EVP_PKEY *pkey; /* server public key */
1424 EVP_MD_CTX ctx; /* signature context */
1425 tstamp_t tstamp, tstamp1 = 0; /* timestamp */
1426 tstamp_t fstamp, fstamp1 = 0; /* filestamp */
1427 u_int vallen; /* value length */
1428 u_int siglen; /* signature length */
1433 * We are extremely parannoyed. We require valid opcode, length,
1434 * association ID, timestamp, filestamp, public key, digest,
1435 * signature length and signature, where relevant. Note that
1436 * preliminary length checks are done in the main loop.
1438 len = ntohl(ep->opcode) & 0x0000ffff;
1439 opcode = ntohl(ep->opcode) & 0xffff0000;
1442 * Check for valid value header, association ID and extension
1443 * field length. Remember, it is not an error to receive an
1444 * unsolicited response; however, the response ID must match
1445 * the association ID.
1447 if (opcode & CRYPTO_ERROR)
1450 if (len < VALUE_LEN)
1453 if (opcode == (CRYPTO_AUTO | CRYPTO_RESP) && (peer->pmode ==
1454 MODE_BROADCAST || (peer->cast_flags & MDF_BCLNT))) {
1455 if (ntohl(ep->associd) != peer->assoc)
1458 if (ntohl(ep->associd) != peer->associd)
1463 * We have a valid value header. Check for valid value and
1464 * signature field lengths. The extension field length must be
1465 * long enough to contain the value header, value and signature.
1466 * Note both the value and signature field lengths are rounded
1467 * up to the next word (4 octets).
1469 vallen = ntohl(ep->vallen);
1471 || vallen > MAX_VALLEN)
1474 i = (vallen + 3) / 4;
1475 siglen = ntohl(ep->pkt[i++]);
1476 if ( siglen > MAX_VALLEN
1477 || len - VALUE_LEN < ((vallen + 3) / 4) * 4
1478 || len - VALUE_LEN - ((vallen + 3) / 4) * 4
1479 < ((siglen + 3) / 4) * 4)
1483 * Check for valid timestamp and filestamp. If the timestamp is
1484 * zero, the sender is not synchronized and signatures are
1485 * not possible. If nonzero the timestamp must not precede the
1486 * filestamp. The timestamp and filestamp must not precede the
1487 * corresponding values in the value structure, if present.
1489 tstamp = ntohl(ep->tstamp);
1490 fstamp = ntohl(ep->fstamp);
1494 if (tstamp < fstamp)
1498 tstamp1 = ntohl(vp->tstamp);
1499 fstamp1 = ntohl(vp->fstamp);
1500 if (tstamp1 != 0 && fstamp1 != 0) {
1501 if (tstamp < tstamp1)
1504 if ((tstamp < fstamp1 || fstamp < fstamp1))
1510 * At the time the certificate message is validated, the public
1511 * key in the message is not available. Thus, don't try to
1512 * verify the signature.
1514 if (opcode == (CRYPTO_CERT | CRYPTO_RESP))
1518 * Check for valid signature length, public key and digest
1521 if (crypto_flags & peer->crypto & CRYPTO_FLAG_PRIV)
1525 if (siglen == 0 || pkey == NULL || peer->digest == NULL)
1528 if (siglen != (u_int)EVP_PKEY_size(pkey))
1532 * Darn, I thought we would never get here. Verify the
1533 * signature. If the identity exchange is verified, light the
1534 * proventic bit. What a relief.
1536 EVP_VerifyInit(&ctx, peer->digest);
1537 /* XXX: the "+ 12" needs to be at least documented... */
1538 EVP_VerifyUpdate(&ctx, (u_char *)&ep->tstamp, vallen + 12);
1539 if (EVP_VerifyFinal(&ctx, (u_char *)&ep->pkt[i], siglen,
1543 if (peer->crypto & CRYPTO_FLAG_VRFY)
1544 peer->crypto |= CRYPTO_FLAG_PROV;
1550 * crypto_encrypt - construct vp (encrypted cookie and signature) from
1551 * the public key and cookie.
1555 * XEVNT_CKY bad or missing cookie
1556 * XEVNT_PUB bad or missing public key
1560 const u_char *ptr, /* Public Key */
1561 u_int vallen, /* Length of Public Key */
1562 keyid_t *cookie, /* server cookie */
1563 struct value *vp /* value pointer */
1566 EVP_PKEY *pkey; /* public key */
1567 EVP_MD_CTX ctx; /* signature context */
1568 tstamp_t tstamp; /* NTP timestamp */
1573 * Extract the public key from the request.
1575 pkey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &ptr, vallen);
1577 msyslog(LOG_ERR, "crypto_encrypt: %s",
1578 ERR_error_string(ERR_get_error(), NULL));
1583 * Encrypt the cookie, encode in ASN.1 and sign.
1585 memset(vp, 0, sizeof(struct value));
1586 tstamp = crypto_time();
1587 vp->tstamp = htonl(tstamp);
1588 vp->fstamp = hostval.tstamp;
1589 vallen = EVP_PKEY_size(pkey);
1590 vp->vallen = htonl(vallen);
1591 vp->ptr = emalloc(vallen);
1593 temp32 = htonl(*cookie);
1594 if (RSA_public_encrypt(4, (u_char *)&temp32, puch,
1595 pkey->pkey.rsa, RSA_PKCS1_OAEP_PADDING) <= 0) {
1596 msyslog(LOG_ERR, "crypto_encrypt: %s",
1597 ERR_error_string(ERR_get_error(), NULL));
1599 EVP_PKEY_free(pkey);
1602 EVP_PKEY_free(pkey);
1606 vp->sig = emalloc(sign_siglen);
1607 EVP_SignInit(&ctx, sign_digest);
1608 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
1609 EVP_SignUpdate(&ctx, vp->ptr, vallen);
1610 if (EVP_SignFinal(&ctx, vp->sig, &vallen, sign_pkey)) {
1611 INSIST(vallen <= sign_siglen);
1612 vp->siglen = htonl(vallen);
1619 * crypto_ident - construct extension field for identity scheme
1621 * This routine determines which identity scheme is in use and
1622 * constructs an extension field for that scheme.
1625 * CRYTPO_IFF IFF scheme
1626 * CRYPTO_GQ GQ scheme
1627 * CRYPTO_MV MV scheme
1628 * CRYPTO_NULL no available scheme
1632 struct peer *peer /* peer structure pointer */
1635 char filename[MAXFILENAME];
1636 const char * scheme_name;
1640 * We come here after the group trusted host has been found; its
1641 * name defines the group name. Search the key cache for all
1642 * keys matching the same group name in order IFF, GQ and MV.
1643 * Use the first one available.
1646 if (peer->crypto & CRYPTO_FLAG_IFF) {
1647 scheme_name = "iff";
1648 scheme_id = CRYPTO_IFF;
1649 } else if (peer->crypto & CRYPTO_FLAG_GQ) {
1651 scheme_id = CRYPTO_GQ;
1652 } else if (peer->crypto & CRYPTO_FLAG_MV) {
1654 scheme_id = CRYPTO_MV;
1657 if (scheme_name != NULL) {
1658 snprintf(filename, sizeof(filename), "ntpkey_%spar_%s",
1659 scheme_name, peer->ident);
1660 peer->ident_pkey = crypto_key(filename, NULL,
1662 if (peer->ident_pkey != NULL)
1667 "crypto_ident: no identity parameters found for group %s",
1675 * crypto_args - construct extension field from arguments
1677 * This routine creates an extension field with current timestamps and
1678 * specified opcode, association ID and optional string. Note that the
1679 * extension field is created here, but freed after the crypto_xmit()
1680 * call in the protocol module.
1682 * Returns extension field pointer (no errors)
1684 * XXX: opcode and len should really be 32-bit quantities and
1685 * we should make sure that str is not too big.
1689 struct peer *peer, /* peer structure pointer */
1690 u_int opcode, /* operation code */
1691 associd_t associd, /* association ID */
1692 char *str /* argument string */
1695 tstamp_t tstamp; /* NTP timestamp */
1696 struct exten *ep; /* extension field pointer */
1697 u_int len; /* extension field length */
1700 tstamp = crypto_time();
1701 len = sizeof(struct exten);
1704 INSIST(slen < MAX_VALLEN);
1707 ep = emalloc_zero(len);
1711 REQUIRE(0 == (len & ~0x0000ffff));
1712 REQUIRE(0 == (opcode & ~0xffff0000));
1714 ep->opcode = htonl(opcode + len);
1715 ep->associd = htonl(associd);
1716 ep->tstamp = htonl(tstamp);
1717 ep->fstamp = hostval.tstamp;
1720 ep->vallen = htonl(slen);
1721 memcpy((char *)ep->pkt, str, slen);
1728 * crypto_send - construct extension field from value components
1730 * The value and signature fields are zero-padded to a word boundary.
1731 * Note: it is not polite to send a nonempty signature with zero
1732 * timestamp or a nonzero timestamp with an empty signature, but those
1733 * rules are not enforced here.
1735 * XXX This code won't work on a box with 16-bit ints.
1739 struct exten *ep, /* extension field pointer */
1740 struct value *vp, /* value pointer */
1741 int start /* buffer offset */
1744 u_int len, vallen, siglen, opcode;
1748 * Calculate extension field length and check for buffer
1749 * overflow. Leave room for the MAC.
1751 len = 16; /* XXX Document! */
1752 vallen = ntohl(vp->vallen);
1753 INSIST(vallen <= MAX_VALLEN);
1754 len += ((vallen + 3) / 4 + 1) * 4;
1755 siglen = ntohl(vp->siglen);
1756 len += ((siglen + 3) / 4 + 1) * 4;
1757 if (start + len > sizeof(struct pkt) - MAX_MAC_LEN)
1763 ep->tstamp = vp->tstamp;
1764 ep->fstamp = vp->fstamp;
1765 ep->vallen = vp->vallen;
1768 * Copy value. If the data field is empty or zero length,
1769 * encode an empty value with length zero.
1772 if (vallen > 0 && vp->ptr != NULL) {
1775 ep->pkt[i + j++] = 0;
1776 memcpy(&ep->pkt[i], vp->ptr, vallen);
1781 * Copy signature. If the signature field is empty or zero
1782 * length, encode an empty signature with length zero.
1784 ep->pkt[i++] = vp->siglen;
1785 if (siglen > 0 && vp->sig != NULL) {
1788 ep->pkt[i + j++] = 0;
1789 memcpy(&ep->pkt[i], vp->sig, siglen);
1790 /* i += j; */ /* We don't use i after this */
1792 opcode = ntohl(ep->opcode);
1793 ep->opcode = htonl((opcode & 0xffff0000) | len);
1794 ENSURE(len <= MAX_VALLEN);
1800 * crypto_update - compute new public value and sign extension fields
1802 * This routine runs periodically, like once a day, and when something
1803 * changes. It updates the timestamps on three value structures and one
1804 * value structure list, then signs all the structures:
1806 * hostval host name (not signed)
1808 * cinfo certificate info/value list
1809 * tai_leap leap values
1811 * Filestamps are proventic data, so this routine runs only when the
1812 * host is synchronized to a proventicated source. Thus, the timestamp
1813 * is proventic and can be used to deflect clogging attacks.
1815 * Returns void (no errors)
1820 EVP_MD_CTX ctx; /* message digest context */
1821 struct cert_info *cp; /* certificate info/value */
1822 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1825 leap_result_t leap_data;
1827 hostval.tstamp = htonl(crypto_time());
1828 if (hostval.tstamp == 0)
1832 * Sign public key and timestamps. The filestamp is derived from
1833 * the host key file extension from wherever the file was
1836 if (pubkey.vallen != 0) {
1837 pubkey.tstamp = hostval.tstamp;
1839 if (pubkey.sig == NULL)
1840 pubkey.sig = emalloc(sign_siglen);
1841 EVP_SignInit(&ctx, sign_digest);
1842 EVP_SignUpdate(&ctx, (u_char *)&pubkey, 12);
1843 EVP_SignUpdate(&ctx, pubkey.ptr, ntohl(pubkey.vallen));
1844 if (EVP_SignFinal(&ctx, pubkey.sig, &len, sign_pkey)) {
1845 INSIST(len <= sign_siglen);
1846 pubkey.siglen = htonl(len);
1851 * Sign certificates and timestamps. The filestamp is derived
1852 * from the certificate file extension from wherever the file
1853 * was generated. Note we do not throw expired certificates
1854 * away; they may have signed younger ones.
1856 for (cp = cinfo; cp != NULL; cp = cp->link) {
1857 cp->cert.tstamp = hostval.tstamp;
1858 cp->cert.siglen = 0;
1859 if (cp->cert.sig == NULL)
1860 cp->cert.sig = emalloc(sign_siglen);
1861 EVP_SignInit(&ctx, sign_digest);
1862 EVP_SignUpdate(&ctx, (u_char *)&cp->cert, 12);
1863 EVP_SignUpdate(&ctx, cp->cert.ptr,
1864 ntohl(cp->cert.vallen));
1865 if (EVP_SignFinal(&ctx, cp->cert.sig, &len, sign_pkey)) {
1866 INSIST(len <= sign_siglen);
1867 cp->cert.siglen = htonl(len);
1872 * Sign leapseconds values and timestamps. Note it is not an
1873 * error to return null values.
1875 tai_leap.tstamp = hostval.tstamp;
1876 tai_leap.fstamp = hostval.fstamp;
1878 /* Get the leap second era. We might need a full lookup early
1879 * after start, when the cache is not yet loaded.
1881 leapsec_frame(&leap_data);
1882 if ( ! memcmp(&leap_data.ebase, &leap_data.ttime, sizeof(vint64))) {
1883 time_t now = time(NULL);
1884 uint32_t nowntp = (uint32_t)now + JAN_1970;
1885 leapsec_query(&leap_data, nowntp, &now);
1888 /* Create the data block. The protocol does not work without. */
1889 len = 3 * sizeof(u_int32);
1890 if (tai_leap.ptr == NULL || ntohl(tai_leap.vallen) != len) {
1892 tai_leap.ptr = emalloc(len);
1893 tai_leap.vallen = htonl(len);
1895 ptr = (u_int32 *)tai_leap.ptr;
1896 if (leap_data.tai_offs > 10) {
1897 /* create a TAI / leap era block. The end time is a
1898 * fake -- maybe we can do better.
1900 ptr[0] = htonl(leap_data.tai_offs);
1901 ptr[1] = htonl(leap_data.ebase.d_s.lo);
1902 if (leap_data.ttime.d_s.hi >= 0)
1903 ptr[2] = htonl(leap_data.ttime.D_s.lo + 7*86400);
1905 ptr[2] = htonl(leap_data.ebase.D_s.lo + 25*86400);
1907 /* no leap era available */
1908 memset(ptr, 0, len);
1910 if (tai_leap.sig == NULL)
1911 tai_leap.sig = emalloc(sign_siglen);
1912 EVP_SignInit(&ctx, sign_digest);
1913 EVP_SignUpdate(&ctx, (u_char *)&tai_leap, 12);
1914 EVP_SignUpdate(&ctx, tai_leap.ptr, len);
1915 if (EVP_SignFinal(&ctx, tai_leap.sig, &len, sign_pkey)) {
1916 INSIST(len <= sign_siglen);
1917 tai_leap.siglen = htonl(len);
1919 crypto_flags |= CRYPTO_FLAG_TAI;
1921 snprintf(statstr, sizeof(statstr), "signature update ts %u",
1922 ntohl(hostval.tstamp));
1923 record_crypto_stats(NULL, statstr);
1924 DPRINTF(1, ("crypto_update: %s\n", statstr));
1928 * crypto_update_taichange - eventually trigger crypto_update
1930 * This is called when a change in 'sys_tai' is detected. This will
1931 * happen shortly after a leap second is detected, but unhappily also
1932 * early after system start; also, the crypto stuff might be unused and
1933 * an unguarded call to crypto_update() causes a crash.
1935 * This function makes sure that there already *is* a valid crypto block
1936 * for the use with autokey, and only calls 'crypto_update()' if it can
1939 * Returns void (no errors)
1942 crypto_update_taichange(void)
1944 static const u_int len = 3 * sizeof(u_int32);
1946 /* check if the signing digest algo is available */
1947 if (sign_digest == NULL || sign_pkey == NULL)
1950 /* check size of TAI extension block */
1951 if (tai_leap.ptr == NULL || ntohl(tai_leap.vallen) != len)
1954 /* crypto_update should at least not crash here! */
1959 * value_free - free value structure components.
1961 * Returns void (no errors)
1965 struct value *vp /* value structure */
1968 if (vp->ptr != NULL)
1970 if (vp->sig != NULL)
1972 memset(vp, 0, sizeof(struct value));
1977 * crypto_time - returns current NTP time.
1979 * Returns NTP seconds if in synch, 0 otherwise
1984 l_fp tstamp; /* NTP time */
1987 if (sys_leap != LEAP_NOTINSYNC)
1988 get_systime(&tstamp);
1989 return (tstamp.l_ui);
1994 * asn_to_calendar - convert ASN1_TIME time structure to struct calendar.
2000 ASN1_TIME *asn1time, /* pointer to ASN1_TIME structure */
2001 struct calendar *pjd /* pointer to result */
2004 size_t len; /* length of ASN1_TIME string */
2005 char v[24]; /* writable copy of ASN1_TIME string */
2006 unsigned long temp; /* result from strtoul */
2009 * Extract time string YYMMDDHHMMSSZ from ASN1 time structure.
2010 * Or YYYYMMDDHHMMSSZ.
2011 * Note that the YY, MM, DD fields start with one, the HH, MM,
2012 * SS fields start with zero and the Z character is ignored.
2013 * Also note that two-digit years less than 50 map to years greater than
2014 * 100. Dontcha love ASN.1? Better than MIL-188.
2016 len = asn1time->length;
2017 REQUIRE(len < sizeof(v));
2018 (void)strncpy(v, (char *)(asn1time->data), len);
2020 temp = strtoul(v+len-3, NULL, 10);
2024 temp = strtoul(v+len-5, NULL, 10);
2028 temp = strtoul(v+len-7, NULL, 10);
2032 temp = strtoul(v+len-9, NULL, 10);
2033 pjd->monthday = temp;
2036 temp = strtoul(v+len-11, NULL, 10);
2040 temp = strtoul(v, NULL, 10);
2041 /* handle two-digit years */
2048 pjd->yearday = pjd->weekday = 0;
2054 * bigdig() - compute a BIGNUM MD5 hash of a BIGNUM number.
2056 * Returns void (no errors)
2060 BIGNUM *bn, /* BIGNUM * from */
2061 BIGNUM *bk /* BIGNUM * to */
2064 EVP_MD_CTX ctx; /* message digest context */
2065 u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
2066 u_char *ptr; /* a BIGNUM as binary string */
2069 len = BN_num_bytes(bn);
2072 EVP_DigestInit(&ctx, EVP_md5());
2073 EVP_DigestUpdate(&ctx, ptr, len);
2074 EVP_DigestFinal(&ctx, dgst, &len);
2075 BN_bin2bn(dgst, len, bk);
2081 ***********************************************************************
2083 * The following routines implement the Schnorr (IFF) identity scheme *
2085 ***********************************************************************
2087 * The Schnorr (IFF) identity scheme is intended for use when
2088 * certificates are generated by some other trusted certificate
2089 * authority and the certificate cannot be used to convey public
2090 * parameters. There are two kinds of files: encrypted server files that
2091 * contain private and public values and nonencrypted client files that
2092 * contain only public values. New generations of server files must be
2093 * securely transmitted to all servers of the group; client files can be
2094 * distributed by any means. The scheme is self contained and
2095 * independent of new generations of host keys, sign keys and
2098 * The IFF values hide in a DSA cuckoo structure which uses the same
2099 * parameters. The values are used by an identity scheme based on DSA
2100 * cryptography and described in Stimson p. 285. The p is a 512-bit
2101 * prime, g a generator of Zp* and q a 160-bit prime that divides p - 1
2102 * and is a qth root of 1 mod p; that is, g^q = 1 mod p. The TA rolls a
2103 * private random group key b (0 < b < q) and public key v = g^b, then
2104 * sends (p, q, g, b) to the servers and (p, q, g, v) to the clients.
2105 * Alice challenges Bob to confirm identity using the protocol described
2110 * The scheme goes like this. Both Alice and Bob have the public primes
2111 * p, q and generator g. The TA gives private key b to Bob and public
2114 * Alice rolls new random challenge r (o < r < q) and sends to Bob in
2115 * the IFF request message. Bob rolls new random k (0 < k < q), then
2116 * computes y = k + b r mod q and x = g^k mod p and sends (y, hash(x))
2117 * to Alice in the response message. Besides making the response
2118 * shorter, the hash makes it effectivey impossible for an intruder to
2119 * solve for b by observing a number of these messages.
2121 * Alice receives the response and computes g^y v^r mod p. After a bit
2122 * of algebra, this simplifies to g^k. If the hash of this result
2123 * matches hash(x), Alice knows that Bob has the group key b. The signed
2124 * response binds this knowledge to Bob's private key and the public key
2125 * previously received in his certificate.
2127 * crypto_alice - construct Alice's challenge in IFF scheme
2131 * XEVNT_ID bad or missing group key
2132 * XEVNT_PUB bad or missing public key
2136 struct peer *peer, /* peer pointer */
2137 struct value *vp /* value pointer */
2140 DSA *dsa; /* IFF parameters */
2141 BN_CTX *bctx; /* BIGNUM context */
2142 EVP_MD_CTX ctx; /* signature context */
2147 * The identity parameters must have correct format and content.
2149 if (peer->ident_pkey == NULL) {
2150 msyslog(LOG_NOTICE, "crypto_alice: scheme unavailable");
2154 if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) {
2155 msyslog(LOG_NOTICE, "crypto_alice: defective key");
2160 * Roll new random r (0 < r < q).
2162 if (peer->iffval != NULL)
2163 BN_free(peer->iffval);
2164 peer->iffval = BN_new();
2165 len = BN_num_bytes(dsa->q);
2166 BN_rand(peer->iffval, len * 8, -1, 1); /* r mod q*/
2167 bctx = BN_CTX_new();
2168 BN_mod(peer->iffval, peer->iffval, dsa->q, bctx);
2172 * Sign and send to Bob. The filestamp is from the local file.
2174 memset(vp, 0, sizeof(struct value));
2175 tstamp = crypto_time();
2176 vp->tstamp = htonl(tstamp);
2177 vp->fstamp = htonl(peer->ident_pkey->fstamp);
2178 vp->vallen = htonl(len);
2179 vp->ptr = emalloc(len);
2180 BN_bn2bin(peer->iffval, vp->ptr);
2184 vp->sig = emalloc(sign_siglen);
2185 EVP_SignInit(&ctx, sign_digest);
2186 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2187 EVP_SignUpdate(&ctx, vp->ptr, len);
2188 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
2189 INSIST(len <= sign_siglen);
2190 vp->siglen = htonl(len);
2197 * crypto_bob - construct Bob's response to Alice's challenge
2201 * XEVNT_ERR protocol error
2202 * XEVNT_ID bad or missing group key
2206 struct exten *ep, /* extension pointer */
2207 struct value *vp /* value pointer */
2210 DSA *dsa; /* IFF parameters */
2211 DSA_SIG *sdsa; /* DSA signature context fake */
2212 BN_CTX *bctx; /* BIGNUM context */
2213 EVP_MD_CTX ctx; /* signature context */
2214 tstamp_t tstamp; /* NTP timestamp */
2215 BIGNUM *bn, *bk, *r;
2217 u_int len; /* extension field value length */
2220 * If the IFF parameters are not valid, something awful
2221 * happened or we are being tormented.
2223 if (iffkey_info == NULL) {
2224 msyslog(LOG_NOTICE, "crypto_bob: scheme unavailable");
2227 dsa = iffkey_info->pkey->pkey.dsa;
2230 * Extract r from the challenge.
2232 len = exten_payload_size(ep);
2233 if (len == 0 || len > MAX_VALLEN)
2235 if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2236 msyslog(LOG_ERR, "crypto_bob: %s",
2237 ERR_error_string(ERR_get_error(), NULL));
2242 * Bob rolls random k (0 < k < q), computes y = k + b r mod q
2243 * and x = g^k mod p, then sends (y, hash(x)) to Alice.
2245 bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2246 sdsa = DSA_SIG_new();
2247 BN_rand(bk, len * 8, -1, 1); /* k */
2248 BN_mod_mul(bn, dsa->priv_key, r, dsa->q, bctx); /* b r mod q */
2250 BN_mod(bn, bn, dsa->q, bctx); /* k + b r mod q */
2251 sdsa->r = BN_dup(bn);
2252 BN_mod_exp(bk, dsa->g, bk, dsa->p, bctx); /* g^k mod p */
2254 sdsa->s = BN_dup(bk);
2256 BN_free(r); BN_free(bn); BN_free(bk);
2259 DSA_print_fp(stdout, dsa, 0);
2263 * Encode the values in ASN.1 and sign. The filestamp is from
2266 len = i2d_DSA_SIG(sdsa, NULL);
2268 msyslog(LOG_ERR, "crypto_bob: %s",
2269 ERR_error_string(ERR_get_error(), NULL));
2273 if (len > MAX_VALLEN) {
2274 msyslog(LOG_ERR, "crypto_bob: signature is too big: %u",
2279 memset(vp, 0, sizeof(struct value));
2280 tstamp = crypto_time();
2281 vp->tstamp = htonl(tstamp);
2282 vp->fstamp = htonl(iffkey_info->fstamp);
2283 vp->vallen = htonl(len);
2286 i2d_DSA_SIG(sdsa, &ptr);
2291 /* XXX: more validation to make sure the sign fits... */
2292 vp->sig = emalloc(sign_siglen);
2293 EVP_SignInit(&ctx, sign_digest);
2294 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2295 EVP_SignUpdate(&ctx, vp->ptr, len);
2296 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
2297 INSIST(len <= sign_siglen);
2298 vp->siglen = htonl(len);
2305 * crypto_iff - verify Bob's response to Alice's challenge
2309 * XEVNT_FSP bad filestamp
2310 * XEVNT_ID bad or missing group key
2311 * XEVNT_PUB bad or missing public key
2315 struct exten *ep, /* extension pointer */
2316 struct peer *peer /* peer structure pointer */
2319 DSA *dsa; /* IFF parameters */
2320 BN_CTX *bctx; /* BIGNUM context */
2321 DSA_SIG *sdsa; /* DSA parameters */
2328 * If the IFF parameters are not valid or no challenge was sent,
2329 * something awful happened or we are being tormented.
2331 if (peer->ident_pkey == NULL) {
2332 msyslog(LOG_NOTICE, "crypto_iff: scheme unavailable");
2335 if (ntohl(ep->fstamp) != peer->ident_pkey->fstamp) {
2336 msyslog(LOG_NOTICE, "crypto_iff: invalid filestamp %u",
2340 if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) {
2341 msyslog(LOG_NOTICE, "crypto_iff: defective key");
2344 if (peer->iffval == NULL) {
2345 msyslog(LOG_NOTICE, "crypto_iff: missing challenge");
2350 * Extract the k + b r and g^k values from the response.
2352 bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2353 len = ntohl(ep->vallen);
2354 ptr = (u_char *)ep->pkt;
2355 if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2356 BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
2357 msyslog(LOG_ERR, "crypto_iff: %s",
2358 ERR_error_string(ERR_get_error(), NULL));
2363 * Compute g^(k + b r) g^(q - b)r mod p.
2365 BN_mod_exp(bn, dsa->pub_key, peer->iffval, dsa->p, bctx);
2366 BN_mod_exp(bk, dsa->g, sdsa->r, dsa->p, bctx);
2367 BN_mod_mul(bn, bn, bk, dsa->p, bctx);
2370 * Verify the hash of the result matches hash(x).
2373 temp = BN_cmp(bn, sdsa->s);
2374 BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
2375 BN_free(peer->iffval);
2376 peer->iffval = NULL;
2381 msyslog(LOG_NOTICE, "crypto_iff: identity not verified");
2387 ***********************************************************************
2389 * The following routines implement the Guillou-Quisquater (GQ) *
2392 ***********************************************************************
2394 * The Guillou-Quisquater (GQ) identity scheme is intended for use when
2395 * the certificate can be used to convey public parameters. The scheme
2396 * uses a X509v3 certificate extension field do convey the public key of
2397 * a private key known only to servers. There are two kinds of files:
2398 * encrypted server files that contain private and public values and
2399 * nonencrypted client files that contain only public values. New
2400 * generations of server files must be securely transmitted to all
2401 * servers of the group; client files can be distributed by any means.
2402 * The scheme is self contained and independent of new generations of
2403 * host keys and sign keys. The scheme is self contained and independent
2404 * of new generations of host keys and sign keys.
2406 * The GQ parameters hide in a RSA cuckoo structure which uses the same
2407 * parameters. The values are used by an identity scheme based on RSA
2408 * cryptography and described in Stimson p. 300 (with errors). The 512-
2409 * bit public modulus is n = p q, where p and q are secret large primes.
2410 * The TA rolls private random group key b as RSA exponent. These values
2411 * are known to all group members.
2413 * When rolling new certificates, a server recomputes the private and
2414 * public keys. The private key u is a random roll, while the public key
2415 * is the inverse obscured by the group key v = (u^-1)^b. These values
2416 * replace the private and public keys normally generated by the RSA
2417 * scheme. Alice challenges Bob to confirm identity using the protocol
2422 * The scheme goes like this. Both Alice and Bob have the same modulus n
2423 * and some random b as the group key. These values are computed and
2424 * distributed in advance via secret means, although only the group key
2425 * b is truly secret. Each has a private random private key u and public
2426 * key (u^-1)^b, although not necessarily the same ones. Bob and Alice
2427 * can regenerate the key pair from time to time without affecting
2428 * operations. The public key is conveyed on the certificate in an
2429 * extension field; the private key is never revealed.
2431 * Alice rolls new random challenge r and sends to Bob in the GQ
2432 * request message. Bob rolls new random k, then computes y = k u^r mod
2433 * n and x = k^b mod n and sends (y, hash(x)) to Alice in the response
2434 * message. Besides making the response shorter, the hash makes it
2435 * effectivey impossible for an intruder to solve for b by observing
2436 * a number of these messages.
2438 * Alice receives the response and computes y^b v^r mod n. After a bit
2439 * of algebra, this simplifies to k^b. If the hash of this result
2440 * matches hash(x), Alice knows that Bob has the group key b. The signed
2441 * response binds this knowledge to Bob's private key and the public key
2442 * previously received in his certificate.
2444 * crypto_alice2 - construct Alice's challenge in GQ scheme
2448 * XEVNT_ID bad or missing group key
2449 * XEVNT_PUB bad or missing public key
2453 struct peer *peer, /* peer pointer */
2454 struct value *vp /* value pointer */
2457 RSA *rsa; /* GQ parameters */
2458 BN_CTX *bctx; /* BIGNUM context */
2459 EVP_MD_CTX ctx; /* signature context */
2464 * The identity parameters must have correct format and content.
2466 if (peer->ident_pkey == NULL)
2469 if ((rsa = peer->ident_pkey->pkey->pkey.rsa) == NULL) {
2470 msyslog(LOG_NOTICE, "crypto_alice2: defective key");
2475 * Roll new random r (0 < r < n).
2477 if (peer->iffval != NULL)
2478 BN_free(peer->iffval);
2479 peer->iffval = BN_new();
2480 len = BN_num_bytes(rsa->n);
2481 BN_rand(peer->iffval, len * 8, -1, 1); /* r mod n */
2482 bctx = BN_CTX_new();
2483 BN_mod(peer->iffval, peer->iffval, rsa->n, bctx);
2487 * Sign and send to Bob. The filestamp is from the local file.
2489 memset(vp, 0, sizeof(struct value));
2490 tstamp = crypto_time();
2491 vp->tstamp = htonl(tstamp);
2492 vp->fstamp = htonl(peer->ident_pkey->fstamp);
2493 vp->vallen = htonl(len);
2494 vp->ptr = emalloc(len);
2495 BN_bn2bin(peer->iffval, vp->ptr);
2499 vp->sig = emalloc(sign_siglen);
2500 EVP_SignInit(&ctx, sign_digest);
2501 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2502 EVP_SignUpdate(&ctx, vp->ptr, len);
2503 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
2504 INSIST(len <= sign_siglen);
2505 vp->siglen = htonl(len);
2512 * crypto_bob2 - construct Bob's response to Alice's challenge
2516 * XEVNT_ERR protocol error
2517 * XEVNT_ID bad or missing group key
2521 struct exten *ep, /* extension pointer */
2522 struct value *vp /* value pointer */
2525 RSA *rsa; /* GQ parameters */
2526 DSA_SIG *sdsa; /* DSA parameters */
2527 BN_CTX *bctx; /* BIGNUM context */
2528 EVP_MD_CTX ctx; /* signature context */
2529 tstamp_t tstamp; /* NTP timestamp */
2530 BIGNUM *r, *k, *g, *y;
2536 * If the GQ parameters are not valid, something awful
2537 * happened or we are being tormented.
2539 if (gqkey_info == NULL) {
2540 msyslog(LOG_NOTICE, "crypto_bob2: scheme unavailable");
2543 rsa = gqkey_info->pkey->pkey.rsa;
2546 * Extract r from the challenge.
2548 len = exten_payload_size(ep);
2549 if (len == 0 || len > MAX_VALLEN)
2551 if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2552 msyslog(LOG_ERR, "crypto_bob2: %s",
2553 ERR_error_string(ERR_get_error(), NULL));
2558 * Bob rolls random k (0 < k < n), computes y = k u^r mod n and
2559 * x = k^b mod n, then sends (y, hash(x)) to Alice.
2561 bctx = BN_CTX_new(); k = BN_new(); g = BN_new(); y = BN_new();
2562 sdsa = DSA_SIG_new();
2563 BN_rand(k, len * 8, -1, 1); /* k */
2564 BN_mod(k, k, rsa->n, bctx);
2565 BN_mod_exp(y, rsa->p, r, rsa->n, bctx); /* u^r mod n */
2566 BN_mod_mul(y, k, y, rsa->n, bctx); /* k u^r mod n */
2567 sdsa->r = BN_dup(y);
2568 BN_mod_exp(g, k, rsa->e, rsa->n, bctx); /* k^b mod n */
2570 sdsa->s = BN_dup(g);
2572 BN_free(r); BN_free(k); BN_free(g); BN_free(y);
2575 RSA_print_fp(stdout, rsa, 0);
2579 * Encode the values in ASN.1 and sign. The filestamp is from
2582 len = s_len = i2d_DSA_SIG(sdsa, NULL);
2584 msyslog(LOG_ERR, "crypto_bob2: %s",
2585 ERR_error_string(ERR_get_error(), NULL));
2589 memset(vp, 0, sizeof(struct value));
2590 tstamp = crypto_time();
2591 vp->tstamp = htonl(tstamp);
2592 vp->fstamp = htonl(gqkey_info->fstamp);
2593 vp->vallen = htonl(len);
2596 i2d_DSA_SIG(sdsa, &ptr);
2601 vp->sig = emalloc(sign_siglen);
2602 EVP_SignInit(&ctx, sign_digest);
2603 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2604 EVP_SignUpdate(&ctx, vp->ptr, len);
2605 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
2606 INSIST(len <= sign_siglen);
2607 vp->siglen = htonl(len);
2614 * crypto_gq - verify Bob's response to Alice's challenge
2618 * XEVNT_ERR protocol error
2619 * XEVNT_FSP bad filestamp
2620 * XEVNT_ID bad or missing group keys
2621 * XEVNT_PUB bad or missing public key
2625 struct exten *ep, /* extension pointer */
2626 struct peer *peer /* peer structure pointer */
2629 RSA *rsa; /* GQ parameters */
2630 BN_CTX *bctx; /* BIGNUM context */
2631 DSA_SIG *sdsa; /* RSA signature context fake */
2638 * If the GQ parameters are not valid or no challenge was sent,
2639 * something awful happened or we are being tormented. Note that
2640 * the filestamp on the local key file can be greater than on
2641 * the remote parameter file if the keys have been refreshed.
2643 if (peer->ident_pkey == NULL) {
2644 msyslog(LOG_NOTICE, "crypto_gq: scheme unavailable");
2647 if (ntohl(ep->fstamp) < peer->ident_pkey->fstamp) {
2648 msyslog(LOG_NOTICE, "crypto_gq: invalid filestamp %u",
2652 if ((rsa = peer->ident_pkey->pkey->pkey.rsa) == NULL) {
2653 msyslog(LOG_NOTICE, "crypto_gq: defective key");
2656 if (peer->iffval == NULL) {
2657 msyslog(LOG_NOTICE, "crypto_gq: missing challenge");
2662 * Extract the y = k u^r and hash(x = k^b) values from the
2665 bctx = BN_CTX_new(); y = BN_new(); v = BN_new();
2666 len = ntohl(ep->vallen);
2667 ptr = (u_char *)ep->pkt;
2668 if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2669 BN_CTX_free(bctx); BN_free(y); BN_free(v);
2670 msyslog(LOG_ERR, "crypto_gq: %s",
2671 ERR_error_string(ERR_get_error(), NULL));
2676 * Compute v^r y^b mod n.
2678 if (peer->grpkey == NULL) {
2679 msyslog(LOG_NOTICE, "crypto_gq: missing group key");
2682 BN_mod_exp(v, peer->grpkey, peer->iffval, rsa->n, bctx);
2684 BN_mod_exp(y, sdsa->r, rsa->e, rsa->n, bctx); /* y^b mod n */
2685 BN_mod_mul(y, v, y, rsa->n, bctx); /* v^r y^b mod n */
2688 * Verify the hash of the result matches hash(x).
2691 temp = BN_cmp(y, sdsa->s);
2692 BN_CTX_free(bctx); BN_free(y); BN_free(v);
2693 BN_free(peer->iffval);
2694 peer->iffval = NULL;
2699 msyslog(LOG_NOTICE, "crypto_gq: identity not verified");
2705 ***********************************************************************
2707 * The following routines implement the Mu-Varadharajan (MV) identity *
2710 ***********************************************************************
2712 * The Mu-Varadharajan (MV) cryptosystem was originally intended when
2713 * servers broadcast messages to clients, but clients never send
2714 * messages to servers. There is one encryption key for the server and a
2715 * separate decryption key for each client. It operated something like a
2716 * pay-per-view satellite broadcasting system where the session key is
2717 * encrypted by the broadcaster and the decryption keys are held in a
2718 * tamperproof set-top box.
2720 * The MV parameters and private encryption key hide in a DSA cuckoo
2721 * structure which uses the same parameters, but generated in a
2722 * different way. The values are used in an encryption scheme similar to
2723 * El Gamal cryptography and a polynomial formed from the expansion of
2724 * product terms (x - x[j]), as described in Mu, Y., and V.
2725 * Varadharajan: Robust and Secure Broadcasting, Proc. Indocrypt 2001,
2726 * 223-231. The paper has significant errors and serious omissions.
2728 * Let q be the product of n distinct primes s1[j] (j = 1...n), where
2729 * each s1[j] has m significant bits. Let p be a prime p = 2 * q + 1, so
2730 * that q and each s1[j] divide p - 1 and p has M = n * m + 1
2731 * significant bits. Let g be a generator of Zp; that is, gcd(g, p - 1)
2732 * = 1 and g^q = 1 mod p. We do modular arithmetic over Zq and then
2733 * project into Zp* as exponents of g. Sometimes we have to compute an
2734 * inverse b^-1 of random b in Zq, but for that purpose we require
2735 * gcd(b, q) = 1. We expect M to be in the 500-bit range and n
2736 * relatively small, like 30. These are the parameters of the scheme and
2737 * they are expensive to compute.
2739 * We set up an instance of the scheme as follows. A set of random
2740 * values x[j] mod q (j = 1...n), are generated as the zeros of a
2741 * polynomial of order n. The product terms (x - x[j]) are expanded to
2742 * form coefficients a[i] mod q (i = 0...n) in powers of x. These are
2743 * used as exponents of the generator g mod p to generate the private
2744 * encryption key A. The pair (gbar, ghat) of public server keys and the
2745 * pairs (xbar[j], xhat[j]) (j = 1...n) of private client keys are used
2746 * to construct the decryption keys. The devil is in the details.
2748 * This routine generates a private server encryption file including the
2749 * private encryption key E and partial decryption keys gbar and ghat.
2750 * It then generates public client decryption files including the public
2751 * keys xbar[j] and xhat[j] for each client j. The partial decryption
2752 * files are used to compute the inverse of E. These values are suitably
2753 * blinded so secrets are not revealed.
2755 * The distinguishing characteristic of this scheme is the capability to
2756 * revoke keys. Included in the calculation of E, gbar and ghat is the
2757 * product s = prod(s1[j]) (j = 1...n) above. If the factor s1[j] is
2758 * subsequently removed from the product and E, gbar and ghat
2759 * recomputed, the jth client will no longer be able to compute E^-1 and
2760 * thus unable to decrypt the messageblock.
2764 * The scheme goes like this. Bob has the server values (p, E, q, gbar,
2765 * ghat) and Alice has the client values (p, xbar, xhat).
2767 * Alice rolls new random nonce r mod p and sends to Bob in the MV
2768 * request message. Bob rolls random nonce k mod q, encrypts y = r E^k
2769 * mod p and sends (y, gbar^k, ghat^k) to Alice.
2771 * Alice receives the response and computes the inverse (E^k)^-1 from
2772 * the partial decryption keys gbar^k, ghat^k, xbar and xhat. She then
2773 * decrypts y and verifies it matches the original r. The signed
2774 * response binds this knowledge to Bob's private key and the public key
2775 * previously received in his certificate.
2777 * crypto_alice3 - construct Alice's challenge in MV scheme
2781 * XEVNT_ID bad or missing group key
2782 * XEVNT_PUB bad or missing public key
2786 struct peer *peer, /* peer pointer */
2787 struct value *vp /* value pointer */
2790 DSA *dsa; /* MV parameters */
2791 BN_CTX *bctx; /* BIGNUM context */
2792 EVP_MD_CTX ctx; /* signature context */
2797 * The identity parameters must have correct format and content.
2799 if (peer->ident_pkey == NULL)
2802 if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) {
2803 msyslog(LOG_NOTICE, "crypto_alice3: defective key");
2808 * Roll new random r (0 < r < q).
2810 if (peer->iffval != NULL)
2811 BN_free(peer->iffval);
2812 peer->iffval = BN_new();
2813 len = BN_num_bytes(dsa->p);
2814 BN_rand(peer->iffval, len * 8, -1, 1); /* r mod p */
2815 bctx = BN_CTX_new();
2816 BN_mod(peer->iffval, peer->iffval, dsa->p, bctx);
2820 * Sign and send to Bob. The filestamp is from the local file.
2822 memset(vp, 0, sizeof(struct value));
2823 tstamp = crypto_time();
2824 vp->tstamp = htonl(tstamp);
2825 vp->fstamp = htonl(peer->ident_pkey->fstamp);
2826 vp->vallen = htonl(len);
2827 vp->ptr = emalloc(len);
2828 BN_bn2bin(peer->iffval, vp->ptr);
2832 vp->sig = emalloc(sign_siglen);
2833 EVP_SignInit(&ctx, sign_digest);
2834 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2835 EVP_SignUpdate(&ctx, vp->ptr, len);
2836 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
2837 INSIST(len <= sign_siglen);
2838 vp->siglen = htonl(len);
2845 * crypto_bob3 - construct Bob's response to Alice's challenge
2849 * XEVNT_ERR protocol error
2853 struct exten *ep, /* extension pointer */
2854 struct value *vp /* value pointer */
2857 DSA *dsa; /* MV parameters */
2858 DSA *sdsa; /* DSA signature context fake */
2859 BN_CTX *bctx; /* BIGNUM context */
2860 EVP_MD_CTX ctx; /* signature context */
2861 tstamp_t tstamp; /* NTP timestamp */
2867 * If the MV parameters are not valid, something awful
2868 * happened or we are being tormented.
2870 if (mvkey_info == NULL) {
2871 msyslog(LOG_NOTICE, "crypto_bob3: scheme unavailable");
2874 dsa = mvkey_info->pkey->pkey.dsa;
2877 * Extract r from the challenge.
2879 len = exten_payload_size(ep);
2880 if (len == 0 || len > MAX_VALLEN)
2882 if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2883 msyslog(LOG_ERR, "crypto_bob3: %s",
2884 ERR_error_string(ERR_get_error(), NULL));
2889 * Bob rolls random k (0 < k < q), making sure it is not a
2890 * factor of q. He then computes y = r A^k and sends (y, gbar^k,
2891 * and ghat^k) to Alice.
2893 bctx = BN_CTX_new(); k = BN_new(); u = BN_new();
2895 sdsa->p = BN_new(); sdsa->q = BN_new(); sdsa->g = BN_new();
2897 BN_rand(k, BN_num_bits(dsa->q), 0, 0);
2898 BN_mod(k, k, dsa->q, bctx);
2899 BN_gcd(u, k, dsa->q, bctx);
2903 BN_mod_exp(u, dsa->g, k, dsa->p, bctx); /* A^k r */
2904 BN_mod_mul(sdsa->p, u, r, dsa->p, bctx);
2905 BN_mod_exp(sdsa->q, dsa->priv_key, k, dsa->p, bctx); /* gbar */
2906 BN_mod_exp(sdsa->g, dsa->pub_key, k, dsa->p, bctx); /* ghat */
2907 BN_CTX_free(bctx); BN_free(k); BN_free(r); BN_free(u);
2910 DSA_print_fp(stdout, sdsa, 0);
2914 * Encode the values in ASN.1 and sign. The filestamp is from
2917 memset(vp, 0, sizeof(struct value));
2918 tstamp = crypto_time();
2919 vp->tstamp = htonl(tstamp);
2920 vp->fstamp = htonl(mvkey_info->fstamp);
2921 len = i2d_DSAparams(sdsa, NULL);
2923 msyslog(LOG_ERR, "crypto_bob3: %s",
2924 ERR_error_string(ERR_get_error(), NULL));
2928 vp->vallen = htonl(len);
2931 i2d_DSAparams(sdsa, &ptr);
2936 vp->sig = emalloc(sign_siglen);
2937 EVP_SignInit(&ctx, sign_digest);
2938 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2939 EVP_SignUpdate(&ctx, vp->ptr, len);
2940 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
2941 INSIST(len <= sign_siglen);
2942 vp->siglen = htonl(len);
2949 * crypto_mv - verify Bob's response to Alice's challenge
2953 * XEVNT_ERR protocol error
2954 * XEVNT_FSP bad filestamp
2955 * XEVNT_ID bad or missing group key
2956 * XEVNT_PUB bad or missing public key
2960 struct exten *ep, /* extension pointer */
2961 struct peer *peer /* peer structure pointer */
2964 DSA *dsa; /* MV parameters */
2965 DSA *sdsa; /* DSA parameters */
2966 BN_CTX *bctx; /* BIGNUM context */
2973 * If the MV parameters are not valid or no challenge was sent,
2974 * something awful happened or we are being tormented.
2976 if (peer->ident_pkey == NULL) {
2977 msyslog(LOG_NOTICE, "crypto_mv: scheme unavailable");
2980 if (ntohl(ep->fstamp) != peer->ident_pkey->fstamp) {
2981 msyslog(LOG_NOTICE, "crypto_mv: invalid filestamp %u",
2985 if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) {
2986 msyslog(LOG_NOTICE, "crypto_mv: defective key");
2989 if (peer->iffval == NULL) {
2990 msyslog(LOG_NOTICE, "crypto_mv: missing challenge");
2995 * Extract the y, gbar and ghat values from the response.
2997 bctx = BN_CTX_new(); k = BN_new(); u = BN_new(); v = BN_new();
2998 len = ntohl(ep->vallen);
2999 ptr = (u_char *)ep->pkt;
3000 if ((sdsa = d2i_DSAparams(NULL, &ptr, len)) == NULL) {
3001 msyslog(LOG_ERR, "crypto_mv: %s",
3002 ERR_error_string(ERR_get_error(), NULL));
3007 * Compute (gbar^xhat ghat^xbar) mod p.
3009 BN_mod_exp(u, sdsa->q, dsa->pub_key, dsa->p, bctx);
3010 BN_mod_exp(v, sdsa->g, dsa->priv_key, dsa->p, bctx);
3011 BN_mod_mul(u, u, v, dsa->p, bctx);
3012 BN_mod_mul(u, u, sdsa->p, dsa->p, bctx);
3015 * The result should match r.
3017 temp = BN_cmp(u, peer->iffval);
3018 BN_CTX_free(bctx); BN_free(k); BN_free(u); BN_free(v);
3019 BN_free(peer->iffval);
3020 peer->iffval = NULL;
3025 msyslog(LOG_NOTICE, "crypto_mv: identity not verified");
3031 ***********************************************************************
3033 * The following routines are used to manipulate certificates *
3035 ***********************************************************************
3038 * cert_sign - sign x509 certificate equest and update value structure.
3040 * The certificate request includes a copy of the host certificate,
3041 * which includes the version number, subject name and public key of the
3042 * host. The resulting certificate includes these values plus the
3043 * serial number, issuer name and valid interval of the server. The
3044 * valid interval extends from the current time to the same time one
3045 * year hence. This may extend the life of the signed certificate beyond
3046 * that of the signer certificate.
3048 * It is convenient to use the NTP seconds of the current time as the
3049 * serial number. In the value structure the timestamp is the current
3050 * time and the filestamp is taken from the extension field. Note this
3051 * routine is called only when the client clock is synchronized to a
3052 * proventic source, so timestamp comparisons are valid.
3054 * The host certificate is valid from the time it was generated for a
3055 * period of one year. A signed certificate is valid from the time of
3056 * signature for a period of one year, but only the host certificate (or
3057 * sign certificate if used) is actually used to encrypt and decrypt
3058 * signatures. The signature trail is built from the client via the
3059 * intermediate servers to the trusted server. Each signature on the
3060 * trail must be valid at the time of signature, but it could happen
3061 * that a signer certificate expire before the signed certificate, which
3062 * remains valid until its expiration.
3066 * XEVNT_CRT bad or missing certificate
3067 * XEVNT_PER host certificate expired
3068 * XEVNT_PUB bad or missing public key
3069 * XEVNT_VFY certificate not verified
3073 struct exten *ep, /* extension field pointer */
3074 struct value *vp /* value pointer */
3077 X509 *req; /* X509 certificate request */
3078 X509 *cert; /* X509 certificate */
3079 X509_EXTENSION *ext; /* certificate extension */
3080 ASN1_INTEGER *serial; /* serial number */
3081 X509_NAME *subj; /* distinguished (common) name */
3082 EVP_PKEY *pkey; /* public key */
3083 EVP_MD_CTX ctx; /* message digest context */
3084 tstamp_t tstamp; /* NTP timestamp */
3085 struct calendar tscal;
3092 * Decode ASN.1 objects and construct certificate structure.
3093 * Make sure the system clock is synchronized to a proventic
3096 tstamp = crypto_time();
3100 len = exten_payload_size(ep);
3101 if (len == 0 || len > MAX_VALLEN)
3103 cptr = (void *)ep->pkt;
3104 if ((req = d2i_X509(NULL, &cptr, len)) == NULL) {
3105 msyslog(LOG_ERR, "cert_sign: %s",
3106 ERR_error_string(ERR_get_error(), NULL));
3110 * Extract public key and check for errors.
3112 if ((pkey = X509_get_pubkey(req)) == NULL) {
3113 msyslog(LOG_ERR, "cert_sign: %s",
3114 ERR_error_string(ERR_get_error(), NULL));
3120 * Generate X509 certificate signed by this server. If this is a
3121 * trusted host, the issuer name is the group name; otherwise,
3122 * it is the host name. Also copy any extensions that might be
3126 X509_set_version(cert, X509_get_version(req));
3127 serial = ASN1_INTEGER_new();
3128 ASN1_INTEGER_set(serial, tstamp);
3129 X509_set_serialNumber(cert, serial);
3130 X509_gmtime_adj(X509_get_notBefore(cert), 0L);
3131 X509_gmtime_adj(X509_get_notAfter(cert), YEAR);
3132 subj = X509_get_issuer_name(cert);
3133 X509_NAME_add_entry_by_txt(subj, "commonName", MBSTRING_ASC,
3134 hostval.ptr, strlen((const char *)hostval.ptr), -1, 0);
3135 subj = X509_get_subject_name(req);
3136 X509_set_subject_name(cert, subj);
3137 X509_set_pubkey(cert, pkey);
3138 temp = X509_get_ext_count(req);
3139 for (i = 0; i < temp; i++) {
3140 ext = X509_get_ext(req, i);
3141 INSIST(X509_add_ext(cert, ext, -1));
3146 * Sign and verify the client certificate, but only if the host
3147 * certificate has not expired.
3149 (void)ntpcal_ntp_to_date(&tscal, tstamp, NULL);
3150 if ((calcomp(&tscal, &(cert_host->first)) < 0)
3151 || (calcomp(&tscal, &(cert_host->last)) > 0)) {
3155 X509_sign(cert, sign_pkey, sign_digest);
3156 if (X509_verify(cert, sign_pkey) <= 0) {
3157 msyslog(LOG_ERR, "cert_sign: %s",
3158 ERR_error_string(ERR_get_error(), NULL));
3162 len = i2d_X509(cert, NULL);
3165 * Build and sign the value structure. We have to sign it here,
3166 * since the response has to be returned right away. This is a
3169 memset(vp, 0, sizeof(struct value));
3170 vp->tstamp = htonl(tstamp);
3171 vp->fstamp = ep->fstamp;
3172 vp->vallen = htonl(len);
3173 vp->ptr = emalloc(len);
3175 i2d_X509(cert, (unsigned char **)(intptr_t)&ptr);
3178 vp->sig = emalloc(sign_siglen);
3179 EVP_SignInit(&ctx, sign_digest);
3180 EVP_SignUpdate(&ctx, (u_char *)vp, 12);
3181 EVP_SignUpdate(&ctx, vp->ptr, len);
3182 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
3183 INSIST(len <= sign_siglen);
3184 vp->siglen = htonl(len);
3189 X509_print_fp(stdout, cert);
3197 * cert_install - install certificate in certificate cache
3199 * This routine encodes an extension field into a certificate info/value
3200 * structure. It searches the certificate list for duplicates and
3201 * expunges whichever is older. Finally, it inserts this certificate
3202 * first on the list.
3204 * Returns certificate info pointer if valid, NULL if not.
3208 struct exten *ep, /* cert info/value */
3209 struct peer *peer /* peer structure */
3212 struct cert_info *cp, *xp, **zp;
3215 * Parse and validate the signed certificate. If valid,
3216 * construct the info/value structure; otherwise, scamper home
3219 if ((cp = cert_parse((u_char *)ep->pkt, (long)ntohl(ep->vallen),
3220 (tstamp_t)ntohl(ep->fstamp))) == NULL)
3224 * Scan certificate list looking for another certificate with
3225 * the same subject and issuer. If another is found with the
3226 * same or older filestamp, unlink it and return the goodies to
3227 * the heap. If another is found with a later filestamp, discard
3228 * the new one and leave the building with the old one.
3230 * Make a note to study this issue again. An earlier certificate
3231 * with a long lifetime might be overtaken by a later
3232 * certificate with a short lifetime, thus invalidating the
3233 * earlier signature. However, we gotta find a way to leak old
3234 * stuff from the cache, so we do it anyway.
3237 for (xp = cinfo; xp != NULL; xp = xp->link) {
3238 if (strcmp(cp->subject, xp->subject) == 0 &&
3239 strcmp(cp->issuer, xp->issuer) == 0) {
3240 if (ntohl(cp->cert.fstamp) <=
3241 ntohl(xp->cert.fstamp)) {
3257 cp->flags |= CERT_VALID;
3264 * cert_hike - verify the signature using the issuer public key
3268 * XEVNT_CRT bad or missing certificate
3269 * XEVNT_PER host certificate expired
3270 * XEVNT_VFY certificate not verified
3274 struct peer *peer, /* peer structure pointer */
3275 struct cert_info *yp /* issuer certificate */
3278 struct cert_info *xp; /* subject certificate */
3279 X509 *cert; /* X509 certificate */
3283 * Save the issuer on the new certificate, but remember the old
3286 if (peer->issuer != NULL)
3288 peer->issuer = estrdup(yp->issuer);
3293 * If subject Y matches issuer Y, then the certificate trail is
3294 * complete. If Y is not trusted, the server certificate has yet
3295 * been signed, so keep trying. Otherwise, save the group key
3296 * and light the valid bit. If the host certificate is trusted,
3297 * do not execute a sign exchange. If no identity scheme is in
3298 * use, light the identity and proventic bits.
3300 if (strcmp(yp->subject, yp->issuer) == 0) {
3301 if (!(yp->flags & CERT_TRUST))
3305 * If the server has an an identity scheme, fetch the
3306 * identity credentials. If not, the identity is
3307 * verified only by the trusted certificate. The next
3308 * signature will set the server proventic.
3310 peer->crypto |= CRYPTO_FLAG_CERT;
3311 peer->grpkey = yp->grpkey;
3312 if (peer->ident == NULL || !(peer->crypto &
3314 peer->crypto |= CRYPTO_FLAG_VRFY;
3318 * If X exists, verify signature X using public key Y.
3323 ptr = (u_char *)xp->cert.ptr;
3324 cert = d2i_X509(NULL, &ptr, ntohl(xp->cert.vallen));
3326 xp->flags |= CERT_ERROR;
3329 if (X509_verify(cert, yp->pkey) <= 0) {
3331 xp->flags |= CERT_ERROR;
3337 * Signature X is valid only if it begins during the
3340 if ((calcomp(&(xp->first), &(yp->first)) < 0)
3341 || (calcomp(&(xp->first), &(yp->last)) > 0)) {
3342 xp->flags |= CERT_ERROR;
3345 xp->flags |= CERT_SIGN;
3351 * cert_parse - parse x509 certificate and create info/value structures.
3353 * The server certificate includes the version number, issuer name,
3354 * subject name, public key and valid date interval. If the issuer name
3355 * is the same as the subject name, the certificate is self signed and
3356 * valid only if the server is configured as trustable. If the names are
3357 * different, another issuer has signed the server certificate and
3358 * vouched for it. In this case the server certificate is valid if
3359 * verified by the issuer public key.
3361 * Returns certificate info/value pointer if valid, NULL if not.
3363 struct cert_info * /* certificate information structure */
3365 const u_char *asn1cert, /* X509 certificate */
3366 long len, /* certificate length */
3367 tstamp_t fstamp /* filestamp */
3370 X509 *cert; /* X509 certificate */
3371 X509_EXTENSION *ext; /* X509v3 extension */
3372 struct cert_info *ret; /* certificate info/value */
3374 char pathbuf[MAXFILENAME];
3378 struct calendar fscal;
3381 * Decode ASN.1 objects and construct certificate structure.
3384 if ((cert = d2i_X509(NULL, &ptr, len)) == NULL) {
3385 msyslog(LOG_ERR, "cert_parse: %s",
3386 ERR_error_string(ERR_get_error(), NULL));
3391 X509_print_fp(stdout, cert);
3395 * Extract version, subject name and public key.
3397 ret = emalloc_zero(sizeof(*ret));
3398 if ((ret->pkey = X509_get_pubkey(cert)) == NULL) {
3399 msyslog(LOG_ERR, "cert_parse: %s",
3400 ERR_error_string(ERR_get_error(), NULL));
3405 ret->version = X509_get_version(cert);
3406 X509_NAME_oneline(X509_get_subject_name(cert), pathbuf,
3408 pch = strstr(pathbuf, "CN=");
3410 msyslog(LOG_NOTICE, "cert_parse: invalid subject %s",
3416 ret->subject = estrdup(pch + 3);
3419 * Extract remaining objects. Note that the NTP serial number is
3420 * the NTP seconds at the time of signing, but this might not be
3421 * the case for other authority. We don't bother to check the
3422 * objects at this time, since the real crunch can happen only
3423 * when the time is valid but not yet certificated.
3425 ret->nid = OBJ_obj2nid(cert->cert_info->signature->algorithm);
3426 ret->digest = (const EVP_MD *)EVP_get_digestbynid(ret->nid);
3428 (u_long)ASN1_INTEGER_get(X509_get_serialNumber(cert));
3429 X509_NAME_oneline(X509_get_issuer_name(cert), pathbuf,
3431 if ((pch = strstr(pathbuf, "CN=")) == NULL) {
3432 msyslog(LOG_NOTICE, "cert_parse: invalid issuer %s",
3438 ret->issuer = estrdup(pch + 3);
3439 asn_to_calendar(X509_get_notBefore(cert), &(ret->first));
3440 asn_to_calendar(X509_get_notAfter(cert), &(ret->last));
3443 * Extract extension fields. These are ad hoc ripoffs of
3444 * currently assigned functions and will certainly be changed
3445 * before prime time.
3447 cnt = X509_get_ext_count(cert);
3448 for (i = 0; i < cnt; i++) {
3449 ext = X509_get_ext(cert, i);
3450 temp = OBJ_obj2nid(ext->object);
3454 * If a key_usage field is present, we decode whether
3455 * this is a trusted or private certificate. This is
3456 * dorky; all we want is to compare NIDs, but OpenSSL
3457 * insists on BIO text strings.
3459 case NID_ext_key_usage:
3460 bp = BIO_new(BIO_s_mem());
3461 X509V3_EXT_print(bp, ext, 0, 0);
3462 BIO_gets(bp, pathbuf, sizeof(pathbuf));
3464 if (strcmp(pathbuf, "Trust Root") == 0)
3465 ret->flags |= CERT_TRUST;
3466 else if (strcmp(pathbuf, "Private") == 0)
3467 ret->flags |= CERT_PRIV;
3468 DPRINTF(1, ("cert_parse: %s: %s\n",
3469 OBJ_nid2ln(temp), pathbuf));
3473 * If a NID_subject_key_identifier field is present, it
3474 * contains the GQ public key.
3476 case NID_subject_key_identifier:
3477 ret->grpkey = BN_bin2bn(&ext->value->data[2],
3478 ext->value->length - 2, NULL);
3481 DPRINTF(1, ("cert_parse: %s\n",
3486 if (strcmp(ret->subject, ret->issuer) == 0) {
3489 * If certificate is self signed, verify signature.
3491 if (X509_verify(cert, ret->pkey) <= 0) {
3493 "cert_parse: signature not verified %s",
3502 * Check for a certificate loop.
3504 if (strcmp((const char *)hostval.ptr, ret->issuer) == 0) {
3506 "cert_parse: certificate trail loop %s",
3515 * Verify certificate valid times. Note that certificates cannot
3518 (void)ntpcal_ntp_to_date(&fscal, fstamp, NULL);
3519 if ((calcomp(&(ret->first), &(ret->last)) > 0)
3520 || (calcomp(&(ret->first), &fscal) < 0)) {
3522 "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",
3524 ret->first.year, ret->first.month, ret->first.monthday,
3525 ret->first.hour, ret->first.minute, ret->first.second,
3526 ret->last.year, ret->last.month, ret->last.monthday,
3527 ret->last.hour, ret->last.minute, ret->last.second,
3528 fscal.year, fscal.month, fscal.monthday,
3529 fscal.hour, fscal.minute, fscal.second);
3536 * Build the value structure to sign and send later.
3538 ret->cert.fstamp = htonl(fstamp);
3539 ret->cert.vallen = htonl(len);
3540 ret->cert.ptr = emalloc(len);
3541 memcpy(ret->cert.ptr, asn1cert, len);
3548 * cert_free - free certificate information structure
3552 struct cert_info *cinf /* certificate info/value structure */
3555 if (cinf->pkey != NULL)
3556 EVP_PKEY_free(cinf->pkey);
3557 if (cinf->subject != NULL)
3558 free(cinf->subject);
3559 if (cinf->issuer != NULL)
3561 if (cinf->grpkey != NULL)
3562 BN_free(cinf->grpkey);
3563 value_free(&cinf->cert);
3569 * crypto_key - load cryptographic parameters and keys
3571 * This routine searches the key cache for matching name in the form
3572 * ntpkey_<key>_<name>, where <key> is one of host, sign, iff, gq, mv,
3573 * and <name> is the host/group name. If not found, it tries to load a
3574 * PEM-encoded file of the same name and extracts the filestamp from
3575 * the first line of the file name. It returns the key pointer if valid,
3578 static struct pkey_info *
3580 char *cp, /* file name */
3581 char *passwd1, /* password */
3582 sockaddr_u *addr /* IP address */
3585 FILE *str; /* file handle */
3586 struct pkey_info *pkp; /* generic key */
3587 EVP_PKEY *pkey = NULL; /* public/private key */
3589 char filename[MAXFILENAME]; /* name of key file */
3590 char linkname[MAXFILENAME]; /* filestamp buffer) */
3591 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3595 * Search the key cache for matching key and name.
3597 for (pkp = pkinfo; pkp != NULL; pkp = pkp->link) {
3598 if (strcmp(cp, pkp->name) == 0)
3603 * Open the key file. If the first character of the file name is
3604 * not '/', prepend the keys directory string. If something goes
3605 * wrong, abandon ship.
3608 strlcpy(filename, cp, sizeof(filename));
3610 snprintf(filename, sizeof(filename), "%s/%s", keysdir,
3612 str = fopen(filename, "r");
3617 * Read the filestamp, which is contained in the first line.
3619 if ((ptr = fgets(linkname, sizeof(linkname), str)) == NULL) {
3620 msyslog(LOG_ERR, "crypto_key: empty file %s",
3625 if ((ptr = strrchr(ptr, '.')) == NULL) {
3626 msyslog(LOG_ERR, "crypto_key: no filestamp %s",
3631 if (sscanf(++ptr, "%u", &fstamp) != 1) {
3632 msyslog(LOG_ERR, "crypto_key: invalid filestamp %s",
3639 * Read and decrypt PEM-encoded private key. If it fails to
3640 * decrypt, game over.
3642 pkey = PEM_read_PrivateKey(str, NULL, NULL, passwd1);
3645 msyslog(LOG_ERR, "crypto_key: %s",
3646 ERR_error_string(ERR_get_error(), NULL));
3651 * Make a new entry in the key cache.
3653 pkp = emalloc(sizeof(struct pkey_info));
3657 pkp->name = estrdup(cp);
3658 pkp->fstamp = fstamp;
3661 * Leave tracks in the cryptostats.
3663 if ((ptr = strrchr(linkname, '\n')) != NULL)
3665 snprintf(statstr, sizeof(statstr), "%s mod %d", &linkname[2],
3666 EVP_PKEY_size(pkey) * 8);
3667 record_crypto_stats(addr, statstr);
3669 DPRINTF(1, ("crypto_key: %s\n", statstr));
3672 if (pkey->type == EVP_PKEY_DSA)
3673 DSA_print_fp(stdout, pkey->pkey.dsa, 0);
3674 else if (pkey->type == EVP_PKEY_RSA)
3675 RSA_print_fp(stdout, pkey->pkey.rsa, 0);
3683 ***********************************************************************
3685 * The following routines are used only at initialization time *
3687 ***********************************************************************
3690 * crypto_cert - load certificate from file
3692 * This routine loads an X.509 RSA or DSA certificate from a file and
3693 * constructs a info/cert value structure for this machine. The
3694 * structure includes a filestamp extracted from the file name. Later
3695 * the certificate can be sent to another machine on request.
3697 * Returns certificate info/value pointer if valid, NULL if not.
3699 static struct cert_info * /* certificate information */
3701 char *cp /* file name */
3704 struct cert_info *ret; /* certificate information */
3705 FILE *str; /* file handle */
3706 char filename[MAXFILENAME]; /* name of certificate file */
3707 char linkname[MAXFILENAME]; /* filestamp buffer */
3708 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3709 tstamp_t fstamp; /* filestamp */
3712 char *name, *header;
3716 * Open the certificate file. If the first character of the file
3717 * name is not '/', prepend the keys directory string. If
3718 * something goes wrong, abandon ship.
3721 strlcpy(filename, cp, sizeof(filename));
3723 snprintf(filename, sizeof(filename), "%s/%s", keysdir,
3725 str = fopen(filename, "r");
3730 * Read the filestamp, which is contained in the first line.
3732 if ((ptr = fgets(linkname, sizeof(linkname), str)) == NULL) {
3733 msyslog(LOG_ERR, "crypto_cert: empty file %s",
3738 if ((ptr = strrchr(ptr, '.')) == NULL) {
3739 msyslog(LOG_ERR, "crypto_cert: no filestamp %s",
3744 if (sscanf(++ptr, "%u", &fstamp) != 1) {
3745 msyslog(LOG_ERR, "crypto_cert: invalid filestamp %s",
3752 * Read PEM-encoded certificate and install.
3754 if (!PEM_read(str, &name, &header, &data, &len)) {
3755 msyslog(LOG_ERR, "crypto_cert: %s",
3756 ERR_error_string(ERR_get_error(), NULL));
3762 if (strcmp(name, "CERTIFICATE") != 0) {
3763 msyslog(LOG_NOTICE, "crypto_cert: wrong PEM type %s",
3772 * Parse certificate and generate info/value structure. The
3773 * pointer and copy nonsense is due something broken in Solaris.
3775 ret = cert_parse(data, len, fstamp);
3780 if ((ptr = strrchr(linkname, '\n')) != NULL)
3782 snprintf(statstr, sizeof(statstr), "%s 0x%x len %lu",
3783 &linkname[2], ret->flags, len);
3784 record_crypto_stats(NULL, statstr);
3785 DPRINTF(1, ("crypto_cert: %s\n", statstr));
3791 * crypto_setup - load keys, certificate and identity parameters
3793 * This routine loads the public/private host key and certificate. If
3794 * available, it loads the public/private sign key, which defaults to
3795 * the host key. The host key must be RSA, but the sign key can be
3796 * either RSA or DSA. If a trusted certificate, it loads the identity
3797 * parameters. In either case, the public key on the certificate must
3798 * agree with the sign key.
3800 * Required but missing files and inconsistent data and errors are
3801 * fatal. Allowing configuration to continue would be hazardous and
3802 * require really messy error checks.
3807 struct pkey_info *pinfo; /* private/public key */
3808 char filename[MAXFILENAME]; /* file name buffer */
3809 char hostname[MAXFILENAME]; /* host name buffer */
3811 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3812 l_fp seed; /* crypto PRNG seed as NTP timestamp */
3818 * Check for correct OpenSSL version and avoid initialization in
3819 * the case of multiple crypto commands.
3821 if (crypto_flags & CRYPTO_FLAG_ENAB) {
3823 "crypto_setup: spurious crypto command");
3826 ssl_check_version();
3829 * Load required random seed file and seed the random number
3830 * generator. Be default, it is found as .rnd in the user home
3831 * directory. The root home directory may be / or /root,
3832 * depending on the system. Wiggle the contents a bit and write
3833 * it back so the sequence does not repeat when we next restart.
3835 if (!RAND_status()) {
3836 if (rand_file == NULL) {
3837 RAND_file_name(filename, sizeof(filename));
3838 randfile = filename;
3839 } else if (*rand_file != '/') {
3840 snprintf(filename, sizeof(filename), "%s/%s",
3841 keysdir, rand_file);
3842 randfile = filename;
3844 randfile = rand_file;
3846 if ((bytes = RAND_load_file(randfile, -1)) == 0) {
3848 "crypto_setup: random seed file %s missing",
3852 arc4random_buf(&seed, sizeof(l_fp));
3853 RAND_seed(&seed, sizeof(l_fp));
3854 RAND_write_file(randfile);
3855 DPRINTF(1, ("crypto_setup: OpenSSL version %lx random seed file %s bytes read %d\n",
3856 SSLeay(), randfile, bytes));
3860 * Initialize structures.
3862 gethostname(hostname, sizeof(hostname));
3863 if (host_filename != NULL)
3864 strlcpy(hostname, host_filename, sizeof(hostname));
3866 passwd = estrdup(hostname);
3867 memset(&hostval, 0, sizeof(hostval));
3868 memset(&pubkey, 0, sizeof(pubkey));
3869 memset(&tai_leap, 0, sizeof(tai_leap));
3872 * Load required host key from file "ntpkey_host_<hostname>". If
3873 * no host key file is not found or has invalid password, life
3874 * as we know it ends. The host key also becomes the default
3877 snprintf(filename, sizeof(filename), "ntpkey_host_%s", hostname);
3878 pinfo = crypto_key(filename, passwd, NULL);
3879 if (pinfo == NULL) {
3881 "crypto_setup: host key file %s not found or corrupt",
3885 if (pinfo->pkey->type != EVP_PKEY_RSA) {
3887 "crypto_setup: host key is not RSA key type");
3890 host_pkey = pinfo->pkey;
3891 sign_pkey = host_pkey;
3892 hostval.fstamp = htonl(pinfo->fstamp);
3895 * Construct public key extension field for agreement scheme.
3897 len = i2d_PublicKey(host_pkey, NULL);
3900 i2d_PublicKey(host_pkey, &ptr);
3901 pubkey.fstamp = hostval.fstamp;
3902 pubkey.vallen = htonl(len);
3905 * Load optional sign key from file "ntpkey_sign_<hostname>". If
3906 * available, it becomes the sign key.
3908 snprintf(filename, sizeof(filename), "ntpkey_sign_%s", hostname);
3909 pinfo = crypto_key(filename, passwd, NULL);
3911 sign_pkey = pinfo->pkey;
3914 * Load required certificate from file "ntpkey_cert_<hostname>".
3916 snprintf(filename, sizeof(filename), "ntpkey_cert_%s", hostname);
3917 cinfo = crypto_cert(filename);
3918 if (cinfo == NULL) {
3920 "crypto_setup: certificate file %s not found or corrupt",
3925 sign_digest = cinfo->digest;
3926 sign_siglen = EVP_PKEY_size(sign_pkey);
3927 if (cinfo->flags & CERT_PRIV)
3928 crypto_flags |= CRYPTO_FLAG_PRIV;
3931 * The certificate must be self-signed.
3933 if (strcmp(cinfo->subject, cinfo->issuer) != 0) {
3935 "crypto_setup: certificate %s is not self-signed",
3939 hostval.ptr = estrdup(cinfo->subject);
3940 hostval.vallen = htonl(strlen(cinfo->subject));
3941 sys_hostname = hostval.ptr;
3942 ptr = (u_char *)strchr(sys_hostname, '@');
3944 sys_groupname = estrdup((char *)++ptr);
3945 if (ident_filename != NULL)
3946 strlcpy(hostname, ident_filename, sizeof(hostname));
3949 * Load optional IFF parameters from file
3950 * "ntpkey_iffkey_<hostname>".
3952 snprintf(filename, sizeof(filename), "ntpkey_iffkey_%s",
3954 iffkey_info = crypto_key(filename, passwd, NULL);
3955 if (iffkey_info != NULL)
3956 crypto_flags |= CRYPTO_FLAG_IFF;
3959 * Load optional GQ parameters from file
3960 * "ntpkey_gqkey_<hostname>".
3962 snprintf(filename, sizeof(filename), "ntpkey_gqkey_%s",
3964 gqkey_info = crypto_key(filename, passwd, NULL);
3965 if (gqkey_info != NULL)
3966 crypto_flags |= CRYPTO_FLAG_GQ;
3969 * Load optional MV parameters from file
3970 * "ntpkey_mvkey_<hostname>".
3972 snprintf(filename, sizeof(filename), "ntpkey_mvkey_%s",
3974 mvkey_info = crypto_key(filename, passwd, NULL);
3975 if (mvkey_info != NULL)
3976 crypto_flags |= CRYPTO_FLAG_MV;
3979 * We met the enemy and he is us. Now strike up the dance.
3981 crypto_flags |= CRYPTO_FLAG_ENAB | (cinfo->nid << 16);
3982 snprintf(statstr, sizeof(statstr), "setup 0x%x host %s %s",
3983 crypto_flags, hostname, OBJ_nid2ln(cinfo->nid));
3984 record_crypto_stats(NULL, statstr);
3985 DPRINTF(1, ("crypto_setup: %s\n", statstr));
3990 * crypto_config - configure data from the crypto command.
3994 int item, /* configuration item */
3995 char *cp /* item name */
4000 DPRINTF(1, ("crypto_config: item %d %s\n", item, cp));
4005 * Set host name (host).
4007 case CRYPTO_CONF_PRIV:
4008 if (NULL != host_filename)
4009 free(host_filename);
4010 host_filename = estrdup(cp);
4014 * Set group name (ident).
4016 case CRYPTO_CONF_IDENT:
4017 if (NULL != ident_filename)
4018 free(ident_filename);
4019 ident_filename = estrdup(cp);
4023 * Set private key password (pw).
4025 case CRYPTO_CONF_PW:
4028 passwd = estrdup(cp);
4032 * Set random seed file name (randfile).
4034 case CRYPTO_CONF_RAND:
4035 if (NULL != rand_file)
4037 rand_file = estrdup(cp);
4041 * Set message digest NID.
4043 case CRYPTO_CONF_NID:
4044 nid = OBJ_sn2nid(cp);
4047 "crypto_config: invalid digest name %s", cp);
4055 * Get the payload size (internal value length) of an extension packet.
4056 * If the inner value size does not match the outer packet size (that
4057 * is, the value would end behind the frame given by the opcode/size
4058 * field) the function will effectively return UINT_MAX. If the frame is
4059 * too short to hold a variable-sized value, the return value is zero.
4063 const struct exten * ep)
4065 typedef const u_char *BPTR;
4073 head_size = (BPTR)(&ep->vallen + 1) - (BPTR)ep;
4074 extn_size = (uint16_t)(ntohl(ep->opcode) & 0x0000ffff);
4075 if (extn_size >= head_size) {
4076 data_size = (uint32_t)ntohl(ep->vallen);
4077 if (data_size > extn_size - head_size)
4078 data_size = ~(size_t)0u;
4081 return (u_int)data_size;
4083 # else /* !AUTOKEY follows */
4084 int ntp_crypto_bs_pubkey;
4085 # endif /* !AUTOKEY */