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 *);
208 readlink(char * link, char * file, int len) {
214 * session_key - generate session key
216 * This routine generates a session key from the source address,
217 * destination address, key ID and private value. The value of the
218 * session key is the MD5 hash of these values, while the next key ID is
219 * the first four octets of the hash.
221 * Returns the next key ID or 0 if there is no destination address.
225 sockaddr_u *srcadr, /* source address */
226 sockaddr_u *dstadr, /* destination address */
227 keyid_t keyno, /* key ID */
228 keyid_t private, /* private value */
229 u_long lifetime /* key lifetime */
232 EVP_MD_CTX ctx; /* message digest context */
233 u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
234 keyid_t keyid; /* key identifer */
235 u_int32 header[10]; /* data in network byte order */
242 * Generate the session key and key ID. If the lifetime is
243 * greater than zero, install the key and call it trusted.
248 header[0] = NSRCADR(srcadr);
249 header[1] = NSRCADR(dstadr);
250 header[2] = htonl(keyno);
251 header[3] = htonl(private);
252 hdlen = 4 * sizeof(u_int32);
256 memcpy(&header[0], PSOCK_ADDR6(srcadr),
257 sizeof(struct in6_addr));
258 memcpy(&header[4], PSOCK_ADDR6(dstadr),
259 sizeof(struct in6_addr));
260 header[8] = htonl(keyno);
261 header[9] = htonl(private);
262 hdlen = 10 * sizeof(u_int32);
265 EVP_DigestInit(&ctx, EVP_get_digestbynid(crypto_nid));
266 EVP_DigestUpdate(&ctx, (u_char *)header, hdlen);
267 EVP_DigestFinal(&ctx, dgst, &len);
268 memcpy(&keyid, dgst, 4);
269 keyid = ntohl(keyid);
271 MD5auth_setkey(keyno, crypto_nid, dgst, len);
272 authtrust(keyno, lifetime);
274 DPRINTF(2, ("session_key: %s > %s %08x %08x hash %08x life %lu\n",
275 stoa(srcadr), stoa(dstadr), keyno,
276 private, keyid, lifetime));
283 * make_keylist - generate key list
287 * XEVNT_ERR protocol error
289 * This routine constructs a pseudo-random sequence by repeatedly
290 * hashing the session key starting from a given source address,
291 * destination address, private value and the next key ID of the
292 * preceeding session key. The last entry on the list is saved along
293 * with its sequence number and public signature.
297 struct peer *peer, /* peer structure pointer */
298 struct interface *dstadr /* interface */
301 EVP_MD_CTX ctx; /* signature context */
302 tstamp_t tstamp; /* NTP timestamp */
303 struct autokey *ap; /* autokey pointer */
304 struct value *vp; /* value pointer */
305 keyid_t keyid = 0; /* next key ID */
306 keyid_t cookie; /* private value */
315 * Allocate the key list if necessary.
317 tstamp = crypto_time();
318 if (peer->keylist == NULL)
319 peer->keylist = eallocarray(NTP_MAXSESSION,
323 * Generate an initial key ID which is unique and greater than
327 keyid = ntp_random() & 0xffffffff;
328 if (keyid <= NTP_MAXKEY)
331 if (authhavekey(keyid))
337 * Generate up to NTP_MAXSESSION session keys. Stop if the
338 * next one would not be unique or not a session key ID or if
339 * it would expire before the next poll. The private value
340 * included in the hash is zero if broadcast mode, the peer
341 * cookie if client mode or the host cookie if symmetric modes.
343 mpoll = 1 << min(peer->ppoll, peer->hpoll);
344 lifetime = min(1U << sys_automax, NTP_MAXSESSION * mpoll);
345 if (peer->hmode == MODE_BROADCAST)
348 cookie = peer->pcookie;
349 for (i = 0; i < NTP_MAXSESSION; i++) {
350 peer->keylist[i] = keyid;
352 keyid = session_key(&dstadr->sin, &peer->srcadr, keyid,
353 cookie, lifetime + mpoll);
355 if (auth_havekey(keyid) || keyid <= NTP_MAXKEY ||
356 lifetime < 0 || tstamp == 0)
361 * Save the last session key ID, sequence number and timestamp,
362 * then sign these values for later retrieval by the clients. Be
363 * careful not to use invalid key media. Use the public values
364 * timestamp as filestamp.
368 vp->ptr = emalloc(sizeof(struct autokey));
369 ap = (struct autokey *)vp->ptr;
370 ap->seq = htonl(peer->keynumber);
371 ap->key = htonl(keyid);
372 vp->tstamp = htonl(tstamp);
373 vp->fstamp = hostval.tstamp;
374 vp->vallen = htonl(sizeof(struct autokey));
378 vp->sig = emalloc(sign_siglen);
379 EVP_SignInit(&ctx, sign_digest);
380 EVP_SignUpdate(&ctx, (u_char *)vp, 12);
381 EVP_SignUpdate(&ctx, vp->ptr, sizeof(struct autokey));
382 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
383 NTP_INSIST(len <= sign_siglen);
384 vp->siglen = htonl(len);
385 peer->flags |= FLAG_ASSOC;
388 DPRINTF(1, ("make_keys: %d %08x %08x ts %u fs %u poll %d\n",
389 peer->keynumber, keyid, cookie, ntohl(vp->tstamp),
390 ntohl(vp->fstamp), peer->hpoll));
396 * crypto_recv - parse extension fields
398 * This routine is called when the packet has been matched to an
399 * association and passed sanity, format and MAC checks. We believe the
400 * extension field values only if the field has proper format and
401 * length, the timestamp and filestamp are valid and the signature has
402 * valid length and is verified. There are a few cases where some values
403 * are believed even if the signature fails, but only if the proventic
408 * XEVNT_ERR protocol error
409 * XEVNT_LEN bad field format or length
413 struct peer *peer, /* peer structure pointer */
414 struct recvbuf *rbufp /* packet buffer pointer */
417 const EVP_MD *dp; /* message digest algorithm */
418 u_int32 *pkt; /* receive packet pointer */
419 struct autokey *ap, *bp; /* autokey pointer */
420 struct exten *ep, *fp; /* extension pointers */
421 struct cert_info *xinfo; /* certificate info pointer */
422 int has_mac; /* length of MAC field */
423 int authlen; /* offset of MAC field */
424 associd_t associd; /* association ID */
425 tstamp_t fstamp = 0; /* filestamp */
426 u_int len; /* extension field length */
427 u_int code; /* extension field opcode */
428 u_int vallen = 0; /* value length */
429 X509 *cert; /* X509 certificate */
430 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
431 keyid_t cookie; /* crumbles */
432 int hismode; /* packet mode */
438 * Initialize. Note that the packet has already been checked for
439 * valid format and extension field lengths. First extract the
440 * field length, command code and association ID in host byte
441 * order. These are used with all commands and modes. Then check
442 * the version number, which must be 2, and length, which must
443 * be at least 8 for requests and VALUE_LEN (24) for responses.
444 * Packets that fail either test sink without a trace. The
445 * association ID is saved only if nonzero.
447 authlen = LEN_PKT_NOMAC;
448 hismode = (int)PKT_MODE((&rbufp->recv_pkt)->li_vn_mode);
449 while ((has_mac = rbufp->recv_length - authlen) > (int)MAX_MAC_LEN) {
450 pkt = (u_int32 *)&rbufp->recv_pkt + authlen / 4;
451 ep = (struct exten *)pkt;
452 code = ntohl(ep->opcode) & 0xffff0000;
453 len = ntohl(ep->opcode) & 0x0000ffff;
454 // HMS: Why pkt[1] instead of ep->associd ?
455 associd = (associd_t)ntohl(pkt[1]);
457 DPRINTF(1, ("crypto_recv: flags 0x%x ext offset %d len %u code 0x%x associd %d\n",
458 peer->crypto, authlen, len, code >> 16,
462 * Check version number and field length. If bad,
463 * quietly ignore the packet.
465 if (((code >> 24) & 0x3f) != CRYPTO_VN || len < 8) {
467 code |= CRYPTO_ERROR;
470 if (len >= VALUE_LEN) {
471 fstamp = ntohl(ep->fstamp);
472 vallen = ntohl(ep->vallen);
474 * Bug 2761: I hope this isn't too early...
477 || len - VALUE_LEN < vallen)
483 * Install status word, host name, signature scheme and
484 * association ID. In OpenSSL the signature algorithm is
485 * bound to the digest algorithm, so the NID completely
486 * defines the signature scheme. Note the request and
487 * response are identical, but neither is validated by
488 * signature. The request is processed here only in
489 * symmetric modes. The server name field might be
490 * useful to implement access controls in future.
495 * If our state machine is running when this
496 * message arrives, the other fellow might have
497 * restarted. However, this could be an
498 * intruder, so just clamp the poll interval and
499 * find out for ourselves. Otherwise, pass the
500 * extension field to the transmit side.
502 if (peer->crypto & CRYPTO_FLAG_CERT) {
507 if (peer->assoc != associd) {
514 fp->associd = htonl(peer->associd);
518 case CRYPTO_ASSOC | CRYPTO_RESP:
521 * Discard the message if it has already been
522 * stored or the message has been amputated.
525 if (peer->assoc != associd)
529 INSIST(len >= VALUE_LEN);
530 if (vallen == 0 || vallen > MAXHOSTNAME ||
531 len - VALUE_LEN < vallen) {
535 DPRINTF(1, ("crypto_recv: ident host 0x%x %d server 0x%x %d\n",
536 crypto_flags, peer->associd, fstamp,
538 temp32 = crypto_flags & CRYPTO_FLAG_MASK;
541 * If the client scheme is PC, the server scheme
542 * must be PC. The public key and identity are
543 * presumed valid, so we skip the certificate
544 * and identity exchanges and move immediately
545 * to the cookie exchange which confirms the
548 if (crypto_flags & CRYPTO_FLAG_PRIV) {
549 if (!(fstamp & CRYPTO_FLAG_PRIV)) {
553 fstamp |= CRYPTO_FLAG_CERT |
554 CRYPTO_FLAG_VRFY | CRYPTO_FLAG_SIGN;
557 * It is an error if either peer supports
558 * identity, but the other does not.
560 } else if (hismode == MODE_ACTIVE || hismode ==
562 if ((temp32 && !(fstamp &
563 CRYPTO_FLAG_MASK)) ||
564 (!temp32 && (fstamp &
565 CRYPTO_FLAG_MASK))) {
572 * Discard the message if the signature digest
573 * NID is not supported.
575 temp32 = (fstamp >> 16) & 0xffff;
577 (const EVP_MD *)EVP_get_digestbynid(temp32);
584 * Save status word, host name and message
585 * digest/signature type. If this is from a
586 * broadcast and the association ID has changed,
587 * request the autokey values.
589 peer->assoc = associd;
590 if (hismode == MODE_SERVER)
591 fstamp |= CRYPTO_FLAG_AUTO;
592 if (!(fstamp & CRYPTO_FLAG_TAI))
593 fstamp |= CRYPTO_FLAG_LEAP;
594 RAND_bytes((u_char *)&peer->hcookie, 4);
595 peer->crypto = fstamp;
597 if (peer->subject != NULL)
599 peer->subject = emalloc(vallen + 1);
600 memcpy(peer->subject, ep->pkt, vallen);
601 peer->subject[vallen] = '\0';
602 if (peer->issuer != NULL)
604 peer->issuer = estrdup(peer->subject);
605 snprintf(statstr, sizeof(statstr),
606 "assoc %d %d host %s %s", peer->associd,
607 peer->assoc, peer->subject,
609 record_crypto_stats(&peer->srcadr, statstr);
610 DPRINTF(1, ("crypto_recv: %s\n", statstr));
614 * Decode X509 certificate in ASN.1 format and extract
615 * the data containing, among other things, subject
616 * name and public key. In the default identification
617 * scheme, the certificate trail is followed to a self
618 * signed trusted certificate.
620 case CRYPTO_CERT | CRYPTO_RESP:
623 * Discard the message if empty or invalid.
628 if ((rval = crypto_verify(ep, NULL, peer)) !=
633 * Scan the certificate list to delete old
634 * versions and link the newest version first on
635 * the list. Then, verify the signature. If the
636 * certificate is bad or missing, just ignore
639 if ((xinfo = cert_install(ep, peer)) == NULL) {
643 if ((rval = cert_hike(peer, xinfo)) != XEVNT_OK)
647 * We plug in the public key and lifetime from
648 * the first certificate received. However, note
649 * that this certificate might not be signed by
650 * the server, so we can't check the
651 * signature/digest NID.
653 if (peer->pkey == NULL) {
654 puch = xinfo->cert.ptr;
655 cert = d2i_X509(NULL, &puch,
656 ntohl(xinfo->cert.vallen));
657 peer->pkey = X509_get_pubkey(cert);
660 peer->flash &= ~TEST8;
662 snprintf(statstr, sizeof(statstr),
663 "cert %s %s 0x%x %s (%u) fs %u",
664 xinfo->subject, xinfo->issuer, xinfo->flags,
665 OBJ_nid2ln(temp32), temp32,
667 record_crypto_stats(&peer->srcadr, statstr);
668 DPRINTF(1, ("crypto_recv: %s\n", statstr));
672 * Schnorr (IFF) identity scheme. This scheme is
673 * designed for use with shared secret server group keys
674 * and where the certificate may be generated by a third
675 * party. The client sends a challenge to the server,
676 * which performs a calculation and returns the result.
677 * A positive result is possible only if both client and
678 * server contain the same secret group key.
680 case CRYPTO_IFF | CRYPTO_RESP:
683 * Discard the message if invalid.
685 if ((rval = crypto_verify(ep, NULL, peer)) !=
690 * If the challenge matches the response, the
691 * server public key, signature and identity are
692 * all verified at the same time. The server is
693 * declared trusted, so we skip further
694 * certificate exchanges and move immediately to
695 * the cookie exchange.
697 if ((rval = crypto_iff(ep, peer)) != XEVNT_OK)
700 peer->crypto |= CRYPTO_FLAG_VRFY;
701 peer->flash &= ~TEST8;
702 snprintf(statstr, sizeof(statstr), "iff %s fs %u",
703 peer->issuer, ntohl(ep->fstamp));
704 record_crypto_stats(&peer->srcadr, statstr);
705 DPRINTF(1, ("crypto_recv: %s\n", statstr));
709 * Guillou-Quisquater (GQ) identity scheme. This scheme
710 * is designed for use with public certificates carrying
711 * the GQ public key in an extension field. The client
712 * sends a challenge to the server, which performs a
713 * calculation and returns the result. A positive result
714 * is possible only if both client and server contain
715 * the same group key and the server has the matching GQ
718 case CRYPTO_GQ | CRYPTO_RESP:
721 * Discard the message if invalid
723 if ((rval = crypto_verify(ep, NULL, peer)) !=
728 * If the challenge matches the response, the
729 * server public key, signature and identity are
730 * all verified at the same time. The server is
731 * declared trusted, so we skip further
732 * certificate exchanges and move immediately to
733 * the cookie exchange.
735 if ((rval = crypto_gq(ep, peer)) != XEVNT_OK)
738 peer->crypto |= CRYPTO_FLAG_VRFY;
739 peer->flash &= ~TEST8;
740 snprintf(statstr, sizeof(statstr), "gq %s fs %u",
741 peer->issuer, ntohl(ep->fstamp));
742 record_crypto_stats(&peer->srcadr, statstr);
743 DPRINTF(1, ("crypto_recv: %s\n", statstr));
747 * Mu-Varadharajan (MV) identity scheme. This scheme is
748 * designed for use with three levels of trust, trusted
749 * host, server and client. The trusted host key is
750 * opaque to servers and clients; the server keys are
751 * opaque to clients and each client key is different.
752 * Client keys can be revoked without requiring new key
755 case CRYPTO_MV | CRYPTO_RESP:
758 * Discard the message if invalid.
760 if ((rval = crypto_verify(ep, NULL, peer)) !=
765 * If the challenge matches the response, the
766 * server public key, signature and identity are
767 * all verified at the same time. The server is
768 * declared trusted, so we skip further
769 * certificate exchanges and move immediately to
770 * the cookie exchange.
772 if ((rval = crypto_mv(ep, peer)) != XEVNT_OK)
775 peer->crypto |= CRYPTO_FLAG_VRFY;
776 peer->flash &= ~TEST8;
777 snprintf(statstr, sizeof(statstr), "mv %s fs %u",
778 peer->issuer, ntohl(ep->fstamp));
779 record_crypto_stats(&peer->srcadr, statstr);
780 DPRINTF(1, ("crypto_recv: %s\n", statstr));
785 * Cookie response in client and symmetric modes. If the
786 * cookie bit is set, the working cookie is the EXOR of
787 * the current and new values.
789 case CRYPTO_COOK | CRYPTO_RESP:
792 * Discard the message if invalid or signature
793 * not verified with respect to the cookie
796 if ((rval = crypto_verify(ep, &peer->cookval,
801 * Decrypt the cookie, hunting all the time for
804 if (vallen == (u_int)EVP_PKEY_size(host_pkey)) {
805 u_int32 *cookiebuf = malloc(
806 RSA_size(host_pkey->pkey.rsa));
812 if (RSA_private_decrypt(vallen,
816 RSA_PKCS1_OAEP_PADDING) != 4) {
821 cookie = ntohl(*cookiebuf);
830 * Install cookie values and light the cookie
831 * bit. If this is not broadcast client mode, we
835 if (hismode == MODE_ACTIVE || hismode ==
837 peer->pcookie = peer->hcookie ^ cookie;
839 peer->pcookie = cookie;
840 peer->crypto |= CRYPTO_FLAG_COOK;
841 peer->flash &= ~TEST8;
842 snprintf(statstr, sizeof(statstr),
843 "cook %x ts %u fs %u", peer->pcookie,
844 ntohl(ep->tstamp), ntohl(ep->fstamp));
845 record_crypto_stats(&peer->srcadr, statstr);
846 DPRINTF(1, ("crypto_recv: %s\n", statstr));
850 * Install autokey values in broadcast client and
851 * symmetric modes. We have to do this every time the
852 * sever/peer cookie changes or a new keylist is
853 * rolled. Ordinarily, this is automatic as this message
854 * is piggybacked on the first NTP packet sent upon
855 * either of these events. Note that a broadcast client
856 * or symmetric peer can receive this response without a
859 case CRYPTO_AUTO | CRYPTO_RESP:
862 * Discard the message if invalid or signature
863 * not verified with respect to the receive
866 if ((rval = crypto_verify(ep, &peer->recval,
871 * Discard the message if a broadcast client and
872 * the association ID does not match. This might
873 * happen if a broacast server restarts the
874 * protocol. A protocol restart will occur at
875 * the next ASSOC message.
877 if ((peer->cast_flags & MDF_BCLNT) &&
878 peer->assoc != associd)
882 * Install autokey values and light the
883 * autokey bit. This is not hard.
888 if (peer->recval.ptr == NULL)
890 emalloc(sizeof(struct autokey));
891 bp = (struct autokey *)peer->recval.ptr;
892 peer->recval.tstamp = ep->tstamp;
893 peer->recval.fstamp = ep->fstamp;
894 ap = (struct autokey *)ep->pkt;
895 bp->seq = ntohl(ap->seq);
896 bp->key = ntohl(ap->key);
897 peer->pkeyid = bp->key;
898 peer->crypto |= CRYPTO_FLAG_AUTO;
899 peer->flash &= ~TEST8;
900 snprintf(statstr, sizeof(statstr),
901 "auto seq %d key %x ts %u fs %u", bp->seq,
902 bp->key, ntohl(ep->tstamp),
904 record_crypto_stats(&peer->srcadr, statstr);
905 DPRINTF(1, ("crypto_recv: %s\n", statstr));
909 * X509 certificate sign response. Validate the
910 * certificate signed by the server and install. Later
911 * this can be provided to clients of this server in
912 * lieu of the self signed certificate in order to
913 * validate the public key.
915 case CRYPTO_SIGN | CRYPTO_RESP:
918 * Discard the message if invalid.
920 if ((rval = crypto_verify(ep, NULL, peer)) !=
925 * Scan the certificate list to delete old
926 * versions and link the newest version first on
929 if ((xinfo = cert_install(ep, peer)) == NULL) {
933 peer->crypto |= CRYPTO_FLAG_SIGN;
934 peer->flash &= ~TEST8;
936 snprintf(statstr, sizeof(statstr),
937 "sign %s %s 0x%x %s (%u) fs %u",
938 xinfo->subject, xinfo->issuer, xinfo->flags,
939 OBJ_nid2ln(temp32), temp32,
941 record_crypto_stats(&peer->srcadr, statstr);
942 DPRINTF(1, ("crypto_recv: %s\n", statstr));
946 * Install leapseconds values. While the leapsecond
947 * values epoch, TAI offset and values expiration epoch
948 * are retained, only the current TAI offset is provided
949 * via the kernel to other applications.
951 case CRYPTO_LEAP | CRYPTO_RESP:
953 * Discard the message if invalid. We can't
954 * compare the value timestamps here, as they
955 * can be updated by different servers.
957 rval = crypto_verify(ep, NULL, peer);
958 if ((rval != XEVNT_OK ) ||
959 (vallen != 3*sizeof(uint32_t)) )
962 /* Check if we can update the basic TAI offset
963 * for our current leap frame. This is a hack
964 * and ignores the time stamps in the autokey
967 if (sys_leap != LEAP_NOTINSYNC)
968 leapsec_autokey_tai(ntohl(ep->pkt[0]),
969 rbufp->recv_time.l_ui, NULL);
970 tai_leap.tstamp = ep->tstamp;
971 tai_leap.fstamp = ep->fstamp;
973 mprintf_event(EVNT_TAI, peer,
974 "%d seconds", ntohl(ep->pkt[0]));
975 peer->crypto |= CRYPTO_FLAG_LEAP;
976 peer->flash &= ~TEST8;
977 snprintf(statstr, sizeof(statstr),
978 "leap TAI offset %d at %u expire %u fs %u",
979 ntohl(ep->pkt[0]), ntohl(ep->pkt[1]),
980 ntohl(ep->pkt[2]), ntohl(ep->fstamp));
981 record_crypto_stats(&peer->srcadr, statstr);
982 DPRINTF(1, ("crypto_recv: %s\n", statstr));
986 * We come here in symmetric modes for miscellaneous
987 * commands that have value fields but are processed on
988 * the transmit side. All we need do here is check for
989 * valid field length. Note that ASSOC is handled
998 if (len < VALUE_LEN) {
1005 * We come here in symmetric modes for requests
1006 * requiring a response (above plus AUTO and LEAP) and
1007 * for responses. If a request, save the extension field
1008 * for later; invalid requests will be caught on the
1009 * transmit side. If an error or invalid response,
1010 * declare a protocol error.
1013 if (code & (CRYPTO_RESP | CRYPTO_ERROR)) {
1015 } else if (peer->cmmd == NULL) {
1017 memcpy(fp, ep, len);
1023 * The first error found terminates the extension field
1024 * scan and we return the laundry to the caller.
1026 if (rval != XEVNT_OK) {
1027 snprintf(statstr, sizeof(statstr),
1028 "%04x %d %02x %s", htonl(ep->opcode),
1029 associd, rval, eventstr(rval));
1030 record_crypto_stats(&peer->srcadr, statstr);
1031 DPRINTF(1, ("crypto_recv: %s\n", statstr));
1034 authlen += (len + 3) / 4 * 4;
1041 * crypto_xmit - construct extension fields
1043 * This routine is called both when an association is configured and
1044 * when one is not. The only case where this matters is to retrieve the
1045 * autokey information, in which case the caller has to provide the
1046 * association ID to match the association.
1048 * Side effect: update the packet offset.
1052 * XEVNT_CRT bad or missing certificate
1053 * XEVNT_ERR protocol error
1054 * XEVNT_LEN bad field format or length
1055 * XEVNT_PER host certificate expired
1059 struct peer *peer, /* peer structure pointer */
1060 struct pkt *xpkt, /* transmit packet pointer */
1061 struct recvbuf *rbufp, /* receive buffer pointer */
1062 int start, /* offset to extension field */
1063 struct exten *ep, /* extension pointer */
1064 keyid_t cookie /* session cookie */
1067 struct exten *fp; /* extension pointers */
1068 struct cert_info *cp, *xp, *yp; /* cert info/value pointer */
1069 sockaddr_u *srcadr_sin; /* source address */
1070 u_int32 *pkt; /* packet pointer */
1071 u_int opcode; /* extension field opcode */
1072 char certname[MAXHOSTNAME + 1]; /* subject name buffer */
1073 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1075 struct calendar tscal;
1084 * Generate the requested extension field request code, length
1085 * and association ID. If this is a response and the host is not
1086 * synchronized, light the error bit and go home.
1088 pkt = (u_int32 *)xpkt + start / 4;
1089 fp = (struct exten *)pkt;
1090 opcode = ntohl(ep->opcode);
1092 srcadr_sin = &peer->srcadr;
1093 if (!(opcode & CRYPTO_RESP))
1094 peer->opcode = ep->opcode;
1096 srcadr_sin = &rbufp->recv_srcadr;
1098 associd = (associd_t) ntohl(ep->associd);
1100 fp->opcode = htonl((opcode & 0xffff0000) | len);
1101 fp->associd = ep->associd;
1103 tstamp = crypto_time();
1104 switch (opcode & 0xffff0000) {
1107 * Send association request and response with status word and
1108 * host name. Note, this message is not signed and the filestamp
1109 * contains only the status word.
1112 case CRYPTO_ASSOC | CRYPTO_RESP:
1113 len = crypto_send(fp, &hostval, start);
1114 fp->fstamp = htonl(crypto_flags);
1118 * Send certificate request. Use the values from the extension
1122 memset(&vtemp, 0, sizeof(vtemp));
1123 vtemp.tstamp = ep->tstamp;
1124 vtemp.fstamp = ep->fstamp;
1125 vtemp.vallen = ep->vallen;
1126 vtemp.ptr = (u_char *)ep->pkt;
1127 len = crypto_send(fp, &vtemp, start);
1131 * Send sign request. Use the host certificate, which is self-
1132 * signed and may or may not be trusted.
1135 (void)ntpcal_ntp_to_date(&tscal, tstamp, NULL);
1136 if ((calcomp(&tscal, &(cert_host->first)) < 0)
1137 || (calcomp(&tscal, &(cert_host->last)) > 0))
1140 len = crypto_send(fp, &cert_host->cert, start);
1144 * Send certificate response. Use the name in the extension
1145 * field to find the certificate in the cache. If the request
1146 * contains no subject name, assume the name of this host. This
1147 * is for backwards compatibility. Private certificates are
1150 * There may be several certificates matching the request. First
1151 * choice is a self-signed trusted certificate; second choice is
1152 * any certificate signed by another host. There is no third
1155 case CRYPTO_CERT | CRYPTO_RESP:
1156 vallen = ntohl(ep->vallen); /* Must be <64k */
1157 if (vallen == 0 || vallen > MAXHOSTNAME ||
1158 len - VALUE_LEN < vallen) {
1164 * Find all public valid certificates with matching
1165 * subject. If a self-signed, trusted certificate is
1166 * found, use that certificate. If not, use the last non
1167 * self-signed certificate.
1169 memcpy(certname, ep->pkt, vallen);
1170 certname[vallen] = '\0';
1172 for (cp = cinfo; cp != NULL; cp = cp->link) {
1173 if (cp->flags & (CERT_PRIV | CERT_ERROR))
1176 if (strcmp(certname, cp->subject) != 0)
1179 if (strcmp(certname, cp->issuer) != 0)
1181 else if (cp ->flags & CERT_TRUST)
1187 * Be careful who you trust. If the certificate is not
1188 * found, return an empty response. Note that we dont
1189 * enforce lifetimes here.
1191 * The timestamp and filestamp are taken from the
1192 * certificate value structure. For all certificates the
1193 * timestamp is the latest signature update time. For
1194 * host and imported certificates the filestamp is the
1195 * creation epoch. For signed certificates the filestamp
1196 * is the creation epoch of the trusted certificate at
1197 * the root of the certificate trail. In principle, this
1198 * allows strong checking for signature masquerade.
1208 len = crypto_send(fp, &xp->cert, start);
1212 * Send challenge in Schnorr (IFF) identity scheme.
1216 break; /* hack attack */
1218 if ((rval = crypto_alice(peer, &vtemp)) == XEVNT_OK) {
1219 len = crypto_send(fp, &vtemp, start);
1225 * Send response in Schnorr (IFF) identity scheme.
1227 case CRYPTO_IFF | CRYPTO_RESP:
1228 if ((rval = crypto_bob(ep, &vtemp)) == XEVNT_OK) {
1229 len = crypto_send(fp, &vtemp, start);
1235 * Send challenge in Guillou-Quisquater (GQ) identity scheme.
1239 break; /* hack attack */
1241 if ((rval = crypto_alice2(peer, &vtemp)) == XEVNT_OK) {
1242 len = crypto_send(fp, &vtemp, start);
1248 * Send response in Guillou-Quisquater (GQ) identity scheme.
1250 case CRYPTO_GQ | CRYPTO_RESP:
1251 if ((rval = crypto_bob2(ep, &vtemp)) == XEVNT_OK) {
1252 len = crypto_send(fp, &vtemp, start);
1258 * Send challenge in MV identity scheme.
1262 break; /* hack attack */
1264 if ((rval = crypto_alice3(peer, &vtemp)) == XEVNT_OK) {
1265 len = crypto_send(fp, &vtemp, start);
1271 * Send response in MV identity scheme.
1273 case CRYPTO_MV | CRYPTO_RESP:
1274 if ((rval = crypto_bob3(ep, &vtemp)) == XEVNT_OK) {
1275 len = crypto_send(fp, &vtemp, start);
1281 * Send certificate sign response. The integrity of the request
1282 * certificate has already been verified on the receive side.
1283 * Sign the response using the local server key. Use the
1284 * filestamp from the request and use the timestamp as the
1285 * current time. Light the error bit if the certificate is
1286 * invalid or contains an unverified signature.
1288 case CRYPTO_SIGN | CRYPTO_RESP:
1289 if ((rval = cert_sign(ep, &vtemp)) == XEVNT_OK) {
1290 len = crypto_send(fp, &vtemp, start);
1296 * Send public key and signature. Use the values from the public
1300 len = crypto_send(fp, &pubkey, start);
1304 * Encrypt and send cookie and signature. Light the error bit if
1305 * anything goes wrong.
1307 case CRYPTO_COOK | CRYPTO_RESP:
1308 vallen = ntohl(ep->vallen); /* Must be <64k */
1310 || (vallen >= MAX_VALLEN)
1311 || (opcode & 0x0000ffff) < VALUE_LEN + vallen) {
1318 tcookie = peer->hcookie;
1319 if ((rval = crypto_encrypt((const u_char *)ep->pkt, vallen, &tcookie, &vtemp))
1321 len = crypto_send(fp, &vtemp, start);
1327 * Find peer and send autokey data and signature in broadcast
1328 * server and symmetric modes. Use the values in the autokey
1329 * structure. If no association is found, either the server has
1330 * restarted with new associations or some perp has replayed an
1331 * old message, in which case light the error bit.
1333 case CRYPTO_AUTO | CRYPTO_RESP:
1335 if ((peer = findpeerbyassoc(associd)) == NULL) {
1340 peer->flags &= ~FLAG_ASSOC;
1341 len = crypto_send(fp, &peer->sndval, start);
1345 * Send leapseconds values and signature. Use the values from
1346 * the tai structure. If no table has been loaded, just send an
1349 case CRYPTO_LEAP | CRYPTO_RESP:
1350 len = crypto_send(fp, &tai_leap, start);
1354 * Default - Send a valid command for unknown requests; send
1355 * an error response for unknown resonses.
1358 if (opcode & CRYPTO_RESP)
1363 * In case of error, flame the log. If a request, toss the
1364 * puppy; if a response, return so the sender can flame, too.
1366 if (rval != XEVNT_OK) {
1369 uint32 = CRYPTO_ERROR;
1371 fp->opcode |= htonl(uint32);
1372 snprintf(statstr, sizeof(statstr),
1373 "%04x %d %02x %s", opcode, associd, rval,
1375 record_crypto_stats(srcadr_sin, statstr);
1376 DPRINTF(1, ("crypto_xmit: %s\n", statstr));
1377 if (!(opcode & CRYPTO_RESP))
1380 DPRINTF(1, ("crypto_xmit: flags 0x%x offset %d len %d code 0x%x associd %d\n",
1381 crypto_flags, start, len, opcode >> 16, associd));
1387 * crypto_verify - verify the extension field value and signature
1391 * XEVNT_ERR protocol error
1392 * XEVNT_FSP bad filestamp
1393 * XEVNT_LEN bad field format or length
1394 * XEVNT_PUB bad or missing public key
1395 * XEVNT_SGL bad signature length
1396 * XEVNT_SIG signature not verified
1397 * XEVNT_TSP bad timestamp
1401 struct exten *ep, /* extension pointer */
1402 struct value *vp, /* value pointer */
1403 struct peer *peer /* peer structure pointer */
1406 EVP_PKEY *pkey; /* server public key */
1407 EVP_MD_CTX ctx; /* signature context */
1408 tstamp_t tstamp, tstamp1 = 0; /* timestamp */
1409 tstamp_t fstamp, fstamp1 = 0; /* filestamp */
1410 u_int vallen; /* value length */
1411 u_int siglen; /* signature length */
1416 * We are extremely parannoyed. We require valid opcode, length,
1417 * association ID, timestamp, filestamp, public key, digest,
1418 * signature length and signature, where relevant. Note that
1419 * preliminary length checks are done in the main loop.
1421 len = ntohl(ep->opcode) & 0x0000ffff;
1422 opcode = ntohl(ep->opcode) & 0xffff0000;
1425 * Check for valid value header, association ID and extension
1426 * field length. Remember, it is not an error to receive an
1427 * unsolicited response; however, the response ID must match
1428 * the association ID.
1430 if (opcode & CRYPTO_ERROR)
1433 if (len < VALUE_LEN)
1436 if (opcode == (CRYPTO_AUTO | CRYPTO_RESP) && (peer->pmode ==
1437 MODE_BROADCAST || (peer->cast_flags & MDF_BCLNT))) {
1438 if (ntohl(ep->associd) != peer->assoc)
1441 if (ntohl(ep->associd) != peer->associd)
1446 * We have a valid value header. Check for valid value and
1447 * signature field lengths. The extension field length must be
1448 * long enough to contain the value header, value and signature.
1449 * Note both the value and signature field lengths are rounded
1450 * up to the next word (4 octets).
1452 vallen = ntohl(ep->vallen);
1454 || vallen > MAX_VALLEN)
1457 i = (vallen + 3) / 4;
1458 siglen = ntohl(ep->pkt[i++]);
1459 if ( siglen > MAX_VALLEN
1460 || len - VALUE_LEN < ((vallen + 3) / 4) * 4
1461 || len - VALUE_LEN - ((vallen + 3) / 4) * 4
1462 < ((siglen + 3) / 4) * 4)
1466 * Check for valid timestamp and filestamp. If the timestamp is
1467 * zero, the sender is not synchronized and signatures are
1468 * not possible. If nonzero the timestamp must not precede the
1469 * filestamp. The timestamp and filestamp must not precede the
1470 * corresponding values in the value structure, if present.
1472 tstamp = ntohl(ep->tstamp);
1473 fstamp = ntohl(ep->fstamp);
1477 if (tstamp < fstamp)
1481 tstamp1 = ntohl(vp->tstamp);
1482 fstamp1 = ntohl(vp->fstamp);
1483 if (tstamp1 != 0 && fstamp1 != 0) {
1484 if (tstamp < tstamp1)
1487 if ((tstamp < fstamp1 || fstamp < fstamp1))
1493 * At the time the certificate message is validated, the public
1494 * key in the message is not available. Thus, don't try to
1495 * verify the signature.
1497 if (opcode == (CRYPTO_CERT | CRYPTO_RESP))
1501 * Check for valid signature length, public key and digest
1504 if (crypto_flags & peer->crypto & CRYPTO_FLAG_PRIV)
1508 if (siglen == 0 || pkey == NULL || peer->digest == NULL)
1511 if (siglen != (u_int)EVP_PKEY_size(pkey))
1515 * Darn, I thought we would never get here. Verify the
1516 * signature. If the identity exchange is verified, light the
1517 * proventic bit. What a relief.
1519 EVP_VerifyInit(&ctx, peer->digest);
1520 /* XXX: the "+ 12" needs to be at least documented... */
1521 EVP_VerifyUpdate(&ctx, (u_char *)&ep->tstamp, vallen + 12);
1522 if (EVP_VerifyFinal(&ctx, (u_char *)&ep->pkt[i], siglen,
1526 if (peer->crypto & CRYPTO_FLAG_VRFY)
1527 peer->crypto |= CRYPTO_FLAG_PROV;
1533 * crypto_encrypt - construct vp (encrypted cookie and signature) from
1534 * the public key and cookie.
1538 * XEVNT_CKY bad or missing cookie
1539 * XEVNT_PUB bad or missing public key
1543 const u_char *ptr, /* Public Key */
1544 u_int vallen, /* Length of Public Key */
1545 keyid_t *cookie, /* server cookie */
1546 struct value *vp /* value pointer */
1549 EVP_PKEY *pkey; /* public key */
1550 EVP_MD_CTX ctx; /* signature context */
1551 tstamp_t tstamp; /* NTP timestamp */
1556 * Extract the public key from the request.
1558 pkey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &ptr, vallen);
1560 msyslog(LOG_ERR, "crypto_encrypt: %s",
1561 ERR_error_string(ERR_get_error(), NULL));
1566 * Encrypt the cookie, encode in ASN.1 and sign.
1568 memset(vp, 0, sizeof(struct value));
1569 tstamp = crypto_time();
1570 vp->tstamp = htonl(tstamp);
1571 vp->fstamp = hostval.tstamp;
1572 vallen = EVP_PKEY_size(pkey);
1573 vp->vallen = htonl(vallen);
1574 vp->ptr = emalloc(vallen);
1576 temp32 = htonl(*cookie);
1577 if (RSA_public_encrypt(4, (u_char *)&temp32, puch,
1578 pkey->pkey.rsa, RSA_PKCS1_OAEP_PADDING) <= 0) {
1579 msyslog(LOG_ERR, "crypto_encrypt: %s",
1580 ERR_error_string(ERR_get_error(), NULL));
1582 EVP_PKEY_free(pkey);
1585 EVP_PKEY_free(pkey);
1589 vp->sig = emalloc(sign_siglen);
1590 EVP_SignInit(&ctx, sign_digest);
1591 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
1592 EVP_SignUpdate(&ctx, vp->ptr, vallen);
1593 if (EVP_SignFinal(&ctx, vp->sig, &vallen, sign_pkey)) {
1594 NTP_INSIST(vallen <= sign_siglen);
1595 vp->siglen = htonl(vallen);
1602 * crypto_ident - construct extension field for identity scheme
1604 * This routine determines which identity scheme is in use and
1605 * constructs an extension field for that scheme.
1608 * CRYTPO_IFF IFF scheme
1609 * CRYPTO_GQ GQ scheme
1610 * CRYPTO_MV MV scheme
1611 * CRYPTO_NULL no available scheme
1615 struct peer *peer /* peer structure pointer */
1618 char filename[MAXFILENAME];
1619 const char * scheme_name;
1623 * We come here after the group trusted host has been found; its
1624 * name defines the group name. Search the key cache for all
1625 * keys matching the same group name in order IFF, GQ and MV.
1626 * Use the first one available.
1629 if (peer->crypto & CRYPTO_FLAG_IFF) {
1630 scheme_name = "iff";
1631 scheme_id = CRYPTO_IFF;
1632 } else if (peer->crypto & CRYPTO_FLAG_GQ) {
1634 scheme_id = CRYPTO_GQ;
1635 } else if (peer->crypto & CRYPTO_FLAG_MV) {
1637 scheme_id = CRYPTO_MV;
1640 if (scheme_name != NULL) {
1641 snprintf(filename, sizeof(filename), "ntpkey_%spar_%s",
1642 scheme_name, peer->ident);
1643 peer->ident_pkey = crypto_key(filename, NULL,
1645 if (peer->ident_pkey != NULL)
1650 "crypto_ident: no identity parameters found for group %s",
1658 * crypto_args - construct extension field from arguments
1660 * This routine creates an extension field with current timestamps and
1661 * specified opcode, association ID and optional string. Note that the
1662 * extension field is created here, but freed after the crypto_xmit()
1663 * call in the protocol module.
1665 * Returns extension field pointer (no errors)
1667 * XXX: opcode and len should really be 32-bit quantities and
1668 * we should make sure that str is not too big.
1672 struct peer *peer, /* peer structure pointer */
1673 u_int opcode, /* operation code */
1674 associd_t associd, /* association ID */
1675 char *str /* argument string */
1678 tstamp_t tstamp; /* NTP timestamp */
1679 struct exten *ep; /* extension field pointer */
1680 u_int len; /* extension field length */
1683 tstamp = crypto_time();
1684 len = sizeof(struct exten);
1687 INSIST(slen < MAX_VALLEN);
1690 ep = emalloc_zero(len);
1694 REQUIRE(0 == (len & ~0x0000ffff));
1695 REQUIRE(0 == (opcode & ~0xffff0000));
1697 ep->opcode = htonl(opcode + len);
1698 ep->associd = htonl(associd);
1699 ep->tstamp = htonl(tstamp);
1700 ep->fstamp = hostval.tstamp;
1703 ep->vallen = htonl(slen);
1704 memcpy((char *)ep->pkt, str, slen);
1711 * crypto_send - construct extension field from value components
1713 * The value and signature fields are zero-padded to a word boundary.
1714 * Note: it is not polite to send a nonempty signature with zero
1715 * timestamp or a nonzero timestamp with an empty signature, but those
1716 * rules are not enforced here.
1718 * XXX This code won't work on a box with 16-bit ints.
1722 struct exten *ep, /* extension field pointer */
1723 struct value *vp, /* value pointer */
1724 int start /* buffer offset */
1727 u_int len, vallen, siglen, opcode;
1731 * Calculate extension field length and check for buffer
1732 * overflow. Leave room for the MAC.
1734 len = 16; /* XXX Document! */
1735 vallen = ntohl(vp->vallen);
1736 INSIST(vallen <= MAX_VALLEN);
1737 len += ((vallen + 3) / 4 + 1) * 4;
1738 siglen = ntohl(vp->siglen);
1739 len += ((siglen + 3) / 4 + 1) * 4;
1740 if (start + len > sizeof(struct pkt) - MAX_MAC_LEN)
1746 ep->tstamp = vp->tstamp;
1747 ep->fstamp = vp->fstamp;
1748 ep->vallen = vp->vallen;
1751 * Copy value. If the data field is empty or zero length,
1752 * encode an empty value with length zero.
1755 if (vallen > 0 && vp->ptr != NULL) {
1758 ep->pkt[i + j++] = 0;
1759 memcpy(&ep->pkt[i], vp->ptr, vallen);
1764 * Copy signature. If the signature field is empty or zero
1765 * length, encode an empty signature with length zero.
1767 ep->pkt[i++] = vp->siglen;
1768 if (siglen > 0 && vp->sig != NULL) {
1771 ep->pkt[i + j++] = 0;
1772 memcpy(&ep->pkt[i], vp->sig, siglen);
1775 opcode = ntohl(ep->opcode);
1776 ep->opcode = htonl((opcode & 0xffff0000) | len);
1777 ENSURE(len <= MAX_VALLEN);
1783 * crypto_update - compute new public value and sign extension fields
1785 * This routine runs periodically, like once a day, and when something
1786 * changes. It updates the timestamps on three value structures and one
1787 * value structure list, then signs all the structures:
1789 * hostval host name (not signed)
1791 * cinfo certificate info/value list
1792 * tai_leap leap values
1794 * Filestamps are proventic data, so this routine runs only when the
1795 * host is synchronized to a proventicated source. Thus, the timestamp
1796 * is proventic and can be used to deflect clogging attacks.
1798 * Returns void (no errors)
1803 EVP_MD_CTX ctx; /* message digest context */
1804 struct cert_info *cp; /* certificate info/value */
1805 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1808 leap_result_t leap_data;
1810 hostval.tstamp = htonl(crypto_time());
1811 if (hostval.tstamp == 0)
1815 * Sign public key and timestamps. The filestamp is derived from
1816 * the host key file extension from wherever the file was
1819 if (pubkey.vallen != 0) {
1820 pubkey.tstamp = hostval.tstamp;
1822 if (pubkey.sig == NULL)
1823 pubkey.sig = emalloc(sign_siglen);
1824 EVP_SignInit(&ctx, sign_digest);
1825 EVP_SignUpdate(&ctx, (u_char *)&pubkey, 12);
1826 EVP_SignUpdate(&ctx, pubkey.ptr, ntohl(pubkey.vallen));
1827 if (EVP_SignFinal(&ctx, pubkey.sig, &len, sign_pkey)) {
1828 NTP_INSIST(len <= sign_siglen);
1829 pubkey.siglen = htonl(len);
1834 * Sign certificates and timestamps. The filestamp is derived
1835 * from the certificate file extension from wherever the file
1836 * was generated. Note we do not throw expired certificates
1837 * away; they may have signed younger ones.
1839 for (cp = cinfo; cp != NULL; cp = cp->link) {
1840 cp->cert.tstamp = hostval.tstamp;
1841 cp->cert.siglen = 0;
1842 if (cp->cert.sig == NULL)
1843 cp->cert.sig = emalloc(sign_siglen);
1844 EVP_SignInit(&ctx, sign_digest);
1845 EVP_SignUpdate(&ctx, (u_char *)&cp->cert, 12);
1846 EVP_SignUpdate(&ctx, cp->cert.ptr,
1847 ntohl(cp->cert.vallen));
1848 if (EVP_SignFinal(&ctx, cp->cert.sig, &len, sign_pkey)) {
1849 NTP_INSIST(len <= sign_siglen);
1850 cp->cert.siglen = htonl(len);
1855 * Sign leapseconds values and timestamps. Note it is not an
1856 * error to return null values.
1858 tai_leap.tstamp = hostval.tstamp;
1859 tai_leap.fstamp = hostval.fstamp;
1861 /* Get the leap second era. We might need a full lookup early
1862 * after start, when the cache is not yet loaded.
1864 leapsec_frame(&leap_data);
1865 if ( ! memcmp(&leap_data.ebase, &leap_data.ttime, sizeof(vint64))) {
1866 time_t now = time(NULL);
1867 uint32_t nowntp = (uint32_t)now + JAN_1970;
1868 leapsec_query(&leap_data, nowntp, &now);
1871 /* Create the data block. The protocol does not work without. */
1872 len = 3 * sizeof(u_int32);
1873 if (tai_leap.ptr == NULL || ntohl(tai_leap.vallen) != len) {
1875 tai_leap.ptr = emalloc(len);
1876 tai_leap.vallen = htonl(len);
1878 ptr = (u_int32 *)tai_leap.ptr;
1879 if (leap_data.tai_offs > 10) {
1880 /* create a TAI / leap era block. The end time is a
1881 * fake -- maybe we can do better.
1883 ptr[0] = htonl(leap_data.tai_offs);
1884 ptr[1] = htonl(leap_data.ebase.d_s.lo);
1885 if (leap_data.ttime.d_s.hi >= 0)
1886 ptr[2] = htonl(leap_data.ttime.D_s.lo + 7*86400);
1888 ptr[2] = htonl(leap_data.ebase.D_s.lo + 25*86400);
1890 /* no leap era available */
1891 memset(ptr, 0, len);
1893 if (tai_leap.sig == NULL)
1894 tai_leap.sig = emalloc(sign_siglen);
1895 EVP_SignInit(&ctx, sign_digest);
1896 EVP_SignUpdate(&ctx, (u_char *)&tai_leap, 12);
1897 EVP_SignUpdate(&ctx, tai_leap.ptr, len);
1898 if (EVP_SignFinal(&ctx, tai_leap.sig, &len, sign_pkey)) {
1899 NTP_INSIST(len <= sign_siglen);
1900 tai_leap.siglen = htonl(len);
1902 crypto_flags |= CRYPTO_FLAG_TAI;
1904 snprintf(statstr, sizeof(statstr), "signature update ts %u",
1905 ntohl(hostval.tstamp));
1906 record_crypto_stats(NULL, statstr);
1907 DPRINTF(1, ("crypto_update: %s\n", statstr));
1911 * crypto_update_taichange - eventually trigger crypto_update
1913 * This is called when a change in 'sys_tai' is detected. This will
1914 * happen shortly after a leap second is detected, but unhappily also
1915 * early after system start; also, the crypto stuff might be unused and
1916 * an unguarded call to crypto_update() causes a crash.
1918 * This function makes sure that there already *is* a valid crypto block
1919 * for the use with autokey, and only calls 'crypto_update()' if it can
1922 * Returns void (no errors)
1925 crypto_update_taichange(void)
1927 static const u_int len = 3 * sizeof(u_int32);
1929 /* check if the signing digest algo is available */
1930 if (sign_digest == NULL || sign_pkey == NULL)
1933 /* check size of TAI extension block */
1934 if (tai_leap.ptr == NULL || ntohl(tai_leap.vallen) != len)
1937 /* crypto_update should at least not crash here! */
1942 * value_free - free value structure components.
1944 * Returns void (no errors)
1948 struct value *vp /* value structure */
1951 if (vp->ptr != NULL)
1953 if (vp->sig != NULL)
1955 memset(vp, 0, sizeof(struct value));
1960 * crypto_time - returns current NTP time.
1962 * Returns NTP seconds if in synch, 0 otherwise
1967 l_fp tstamp; /* NTP time */
1970 if (sys_leap != LEAP_NOTINSYNC)
1971 get_systime(&tstamp);
1972 return (tstamp.l_ui);
1977 * asn_to_calendar - convert ASN1_TIME time structure to struct calendar.
1983 ASN1_TIME *asn1time, /* pointer to ASN1_TIME structure */
1984 struct calendar *pjd /* pointer to result */
1987 size_t len; /* length of ASN1_TIME string */
1988 char v[24]; /* writable copy of ASN1_TIME string */
1989 unsigned long temp; /* result from strtoul */
1992 * Extract time string YYMMDDHHMMSSZ from ASN1 time structure.
1993 * Or YYYYMMDDHHMMSSZ.
1994 * Note that the YY, MM, DD fields start with one, the HH, MM,
1995 * SS fields start with zero and the Z character is ignored.
1996 * Also note that two-digit years less than 50 map to years greater than
1997 * 100. Dontcha love ASN.1? Better than MIL-188.
1999 len = asn1time->length;
2000 NTP_REQUIRE(len < sizeof(v));
2001 (void)strncpy(v, (char *)(asn1time->data), len);
2002 NTP_REQUIRE(len >= 13);
2003 temp = strtoul(v+len-3, NULL, 10);
2007 temp = strtoul(v+len-5, NULL, 10);
2011 temp = strtoul(v+len-7, NULL, 10);
2015 temp = strtoul(v+len-9, NULL, 10);
2016 pjd->monthday = temp;
2019 temp = strtoul(v+len-11, NULL, 10);
2023 temp = strtoul(v, NULL, 10);
2024 /* handle two-digit years */
2031 pjd->yearday = pjd->weekday = 0;
2037 * bigdig() - compute a BIGNUM MD5 hash of a BIGNUM number.
2039 * Returns void (no errors)
2043 BIGNUM *bn, /* BIGNUM * from */
2044 BIGNUM *bk /* BIGNUM * to */
2047 EVP_MD_CTX ctx; /* message digest context */
2048 u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
2049 u_char *ptr; /* a BIGNUM as binary string */
2052 len = BN_num_bytes(bn);
2055 EVP_DigestInit(&ctx, EVP_md5());
2056 EVP_DigestUpdate(&ctx, ptr, len);
2057 EVP_DigestFinal(&ctx, dgst, &len);
2058 BN_bin2bn(dgst, len, bk);
2064 ***********************************************************************
2066 * The following routines implement the Schnorr (IFF) identity scheme *
2068 ***********************************************************************
2070 * The Schnorr (IFF) identity scheme is intended for use when
2071 * certificates are generated by some other trusted certificate
2072 * authority and the certificate cannot be used to convey public
2073 * parameters. There are two kinds of files: encrypted server files that
2074 * contain private and public values and nonencrypted client files that
2075 * contain only public values. New generations of server files must be
2076 * securely transmitted to all servers of the group; client files can be
2077 * distributed by any means. The scheme is self contained and
2078 * independent of new generations of host keys, sign keys and
2081 * The IFF values hide in a DSA cuckoo structure which uses the same
2082 * parameters. The values are used by an identity scheme based on DSA
2083 * cryptography and described in Stimson p. 285. The p is a 512-bit
2084 * prime, g a generator of Zp* and q a 160-bit prime that divides p - 1
2085 * and is a qth root of 1 mod p; that is, g^q = 1 mod p. The TA rolls a
2086 * private random group key b (0 < b < q) and public key v = g^b, then
2087 * sends (p, q, g, b) to the servers and (p, q, g, v) to the clients.
2088 * Alice challenges Bob to confirm identity using the protocol described
2093 * The scheme goes like this. Both Alice and Bob have the public primes
2094 * p, q and generator g. The TA gives private key b to Bob and public
2097 * Alice rolls new random challenge r (o < r < q) and sends to Bob in
2098 * the IFF request message. Bob rolls new random k (0 < k < q), then
2099 * computes y = k + b r mod q and x = g^k mod p and sends (y, hash(x))
2100 * to Alice in the response message. Besides making the response
2101 * shorter, the hash makes it effectivey impossible for an intruder to
2102 * solve for b by observing a number of these messages.
2104 * Alice receives the response and computes g^y v^r mod p. After a bit
2105 * of algebra, this simplifies to g^k. If the hash of this result
2106 * matches hash(x), Alice knows that Bob has the group key b. The signed
2107 * response binds this knowledge to Bob's private key and the public key
2108 * previously received in his certificate.
2110 * crypto_alice - construct Alice's challenge in IFF scheme
2114 * XEVNT_ID bad or missing group key
2115 * XEVNT_PUB bad or missing public key
2119 struct peer *peer, /* peer pointer */
2120 struct value *vp /* value pointer */
2123 DSA *dsa; /* IFF parameters */
2124 BN_CTX *bctx; /* BIGNUM context */
2125 EVP_MD_CTX ctx; /* signature context */
2130 * The identity parameters must have correct format and content.
2132 if (peer->ident_pkey == NULL) {
2133 msyslog(LOG_NOTICE, "crypto_alice: scheme unavailable");
2137 if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) {
2138 msyslog(LOG_NOTICE, "crypto_alice: defective key");
2143 * Roll new random r (0 < r < q).
2145 if (peer->iffval != NULL)
2146 BN_free(peer->iffval);
2147 peer->iffval = BN_new();
2148 len = BN_num_bytes(dsa->q);
2149 BN_rand(peer->iffval, len * 8, -1, 1); /* r mod q*/
2150 bctx = BN_CTX_new();
2151 BN_mod(peer->iffval, peer->iffval, dsa->q, bctx);
2155 * Sign and send to Bob. The filestamp is from the local file.
2157 memset(vp, 0, sizeof(struct value));
2158 tstamp = crypto_time();
2159 vp->tstamp = htonl(tstamp);
2160 vp->fstamp = htonl(peer->ident_pkey->fstamp);
2161 vp->vallen = htonl(len);
2162 vp->ptr = emalloc(len);
2163 BN_bn2bin(peer->iffval, vp->ptr);
2167 vp->sig = emalloc(sign_siglen);
2168 EVP_SignInit(&ctx, sign_digest);
2169 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2170 EVP_SignUpdate(&ctx, vp->ptr, len);
2171 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
2172 NTP_INSIST(len <= sign_siglen);
2173 vp->siglen = htonl(len);
2180 * crypto_bob - construct Bob's response to Alice's challenge
2184 * XEVNT_ERR protocol error
2185 * XEVNT_ID bad or missing group key
2189 struct exten *ep, /* extension pointer */
2190 struct value *vp /* value pointer */
2193 DSA *dsa; /* IFF parameters */
2194 DSA_SIG *sdsa; /* DSA signature context fake */
2195 BN_CTX *bctx; /* BIGNUM context */
2196 EVP_MD_CTX ctx; /* signature context */
2197 tstamp_t tstamp; /* NTP timestamp */
2198 BIGNUM *bn, *bk, *r;
2200 u_int len; /* extension field length */
2201 u_int vallen = 0; /* value length */
2204 * If the IFF parameters are not valid, something awful
2205 * happened or we are being tormented.
2207 if (iffkey_info == NULL) {
2208 msyslog(LOG_NOTICE, "crypto_bob: scheme unavailable");
2211 dsa = iffkey_info->pkey->pkey.dsa;
2214 * Extract r from the challenge.
2216 vallen = ntohl(ep->vallen);
2217 len = ntohl(ep->opcode) & 0x0000ffff;
2218 if (vallen == 0 || len < VALUE_LEN || len - VALUE_LEN < vallen)
2220 if ((r = BN_bin2bn((u_char *)ep->pkt, vallen, NULL)) == NULL) {
2221 msyslog(LOG_ERR, "crypto_bob: %s",
2222 ERR_error_string(ERR_get_error(), NULL));
2227 * Bob rolls random k (0 < k < q), computes y = k + b r mod q
2228 * and x = g^k mod p, then sends (y, hash(x)) to Alice.
2230 bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2231 sdsa = DSA_SIG_new();
2232 BN_rand(bk, vallen * 8, -1, 1); /* k */
2233 BN_mod_mul(bn, dsa->priv_key, r, dsa->q, bctx); /* b r mod q */
2235 BN_mod(bn, bn, dsa->q, bctx); /* k + b r mod q */
2236 sdsa->r = BN_dup(bn);
2237 BN_mod_exp(bk, dsa->g, bk, dsa->p, bctx); /* g^k mod p */
2239 sdsa->s = BN_dup(bk);
2241 BN_free(r); BN_free(bn); BN_free(bk);
2244 DSA_print_fp(stdout, dsa, 0);
2248 * Encode the values in ASN.1 and sign. The filestamp is from
2251 vallen = i2d_DSA_SIG(sdsa, NULL);
2253 msyslog(LOG_ERR, "crypto_bob: %s",
2254 ERR_error_string(ERR_get_error(), NULL));
2258 if (vallen > MAX_VALLEN) {
2259 msyslog(LOG_ERR, "crypto_bob: signature is too big: %d",
2264 memset(vp, 0, sizeof(struct value));
2265 tstamp = crypto_time();
2266 vp->tstamp = htonl(tstamp);
2267 vp->fstamp = htonl(iffkey_info->fstamp);
2268 vp->vallen = htonl(vallen);
2269 ptr = emalloc(vallen);
2271 i2d_DSA_SIG(sdsa, &ptr);
2276 /* XXX: more validation to make sure the sign fits... */
2277 vp->sig = emalloc(sign_siglen);
2278 EVP_SignInit(&ctx, sign_digest);
2279 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2280 EVP_SignUpdate(&ctx, vp->ptr, vallen);
2281 if (EVP_SignFinal(&ctx, vp->sig, &vallen, sign_pkey)) {
2282 NTP_INSIST(vallen <= sign_siglen);
2283 vp->siglen = htonl(vallen);
2290 * crypto_iff - verify Bob's response to Alice's challenge
2294 * XEVNT_FSP bad filestamp
2295 * XEVNT_ID bad or missing group key
2296 * XEVNT_PUB bad or missing public key
2300 struct exten *ep, /* extension pointer */
2301 struct peer *peer /* peer structure pointer */
2304 DSA *dsa; /* IFF parameters */
2305 BN_CTX *bctx; /* BIGNUM context */
2306 DSA_SIG *sdsa; /* DSA parameters */
2313 * If the IFF parameters are not valid or no challenge was sent,
2314 * something awful happened or we are being tormented.
2316 if (peer->ident_pkey == NULL) {
2317 msyslog(LOG_NOTICE, "crypto_iff: scheme unavailable");
2320 if (ntohl(ep->fstamp) != peer->ident_pkey->fstamp) {
2321 msyslog(LOG_NOTICE, "crypto_iff: invalid filestamp %u",
2325 if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) {
2326 msyslog(LOG_NOTICE, "crypto_iff: defective key");
2329 if (peer->iffval == NULL) {
2330 msyslog(LOG_NOTICE, "crypto_iff: missing challenge");
2335 * Extract the k + b r and g^k values from the response.
2337 bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2338 len = ntohl(ep->vallen);
2339 ptr = (u_char *)ep->pkt;
2340 if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2341 BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
2342 msyslog(LOG_ERR, "crypto_iff: %s",
2343 ERR_error_string(ERR_get_error(), NULL));
2348 * Compute g^(k + b r) g^(q - b)r mod p.
2350 BN_mod_exp(bn, dsa->pub_key, peer->iffval, dsa->p, bctx);
2351 BN_mod_exp(bk, dsa->g, sdsa->r, dsa->p, bctx);
2352 BN_mod_mul(bn, bn, bk, dsa->p, bctx);
2355 * Verify the hash of the result matches hash(x).
2358 temp = BN_cmp(bn, sdsa->s);
2359 BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
2360 BN_free(peer->iffval);
2361 peer->iffval = NULL;
2366 msyslog(LOG_NOTICE, "crypto_iff: identity not verified");
2372 ***********************************************************************
2374 * The following routines implement the Guillou-Quisquater (GQ) *
2377 ***********************************************************************
2379 * The Guillou-Quisquater (GQ) identity scheme is intended for use when
2380 * the certificate can be used to convey public parameters. The scheme
2381 * uses a X509v3 certificate extension field do convey the public key of
2382 * a private key known only to servers. There are two kinds of files:
2383 * encrypted server files that contain private and public values and
2384 * nonencrypted client files that contain only public values. New
2385 * generations of server files must be securely transmitted to all
2386 * servers of the group; client files can be distributed by any means.
2387 * The scheme is self contained and independent of new generations of
2388 * host keys and sign keys. The scheme is self contained and independent
2389 * of new generations of host keys and sign keys.
2391 * The GQ parameters hide in a RSA cuckoo structure which uses the same
2392 * parameters. The values are used by an identity scheme based on RSA
2393 * cryptography and described in Stimson p. 300 (with errors). The 512-
2394 * bit public modulus is n = p q, where p and q are secret large primes.
2395 * The TA rolls private random group key b as RSA exponent. These values
2396 * are known to all group members.
2398 * When rolling new certificates, a server recomputes the private and
2399 * public keys. The private key u is a random roll, while the public key
2400 * is the inverse obscured by the group key v = (u^-1)^b. These values
2401 * replace the private and public keys normally generated by the RSA
2402 * scheme. Alice challenges Bob to confirm identity using the protocol
2407 * The scheme goes like this. Both Alice and Bob have the same modulus n
2408 * and some random b as the group key. These values are computed and
2409 * distributed in advance via secret means, although only the group key
2410 * b is truly secret. Each has a private random private key u and public
2411 * key (u^-1)^b, although not necessarily the same ones. Bob and Alice
2412 * can regenerate the key pair from time to time without affecting
2413 * operations. The public key is conveyed on the certificate in an
2414 * extension field; the private key is never revealed.
2416 * Alice rolls new random challenge r and sends to Bob in the GQ
2417 * request message. Bob rolls new random k, then computes y = k u^r mod
2418 * n and x = k^b mod n and sends (y, hash(x)) to Alice in the response
2419 * message. Besides making the response shorter, the hash makes it
2420 * effectivey impossible for an intruder to solve for b by observing
2421 * a number of these messages.
2423 * Alice receives the response and computes y^b v^r mod n. After a bit
2424 * of algebra, this simplifies to k^b. If the hash of this result
2425 * matches hash(x), Alice knows that Bob has the group key b. The signed
2426 * response binds this knowledge to Bob's private key and the public key
2427 * previously received in his certificate.
2429 * crypto_alice2 - construct Alice's challenge in GQ scheme
2433 * XEVNT_ID bad or missing group key
2434 * XEVNT_PUB bad or missing public key
2438 struct peer *peer, /* peer pointer */
2439 struct value *vp /* value pointer */
2442 RSA *rsa; /* GQ parameters */
2443 BN_CTX *bctx; /* BIGNUM context */
2444 EVP_MD_CTX ctx; /* signature context */
2449 * The identity parameters must have correct format and content.
2451 if (peer->ident_pkey == NULL)
2454 if ((rsa = peer->ident_pkey->pkey->pkey.rsa) == NULL) {
2455 msyslog(LOG_NOTICE, "crypto_alice2: defective key");
2460 * Roll new random r (0 < r < n).
2462 if (peer->iffval != NULL)
2463 BN_free(peer->iffval);
2464 peer->iffval = BN_new();
2465 len = BN_num_bytes(rsa->n);
2466 BN_rand(peer->iffval, len * 8, -1, 1); /* r mod n */
2467 bctx = BN_CTX_new();
2468 BN_mod(peer->iffval, peer->iffval, rsa->n, bctx);
2472 * Sign and send to Bob. The filestamp is from the local file.
2474 memset(vp, 0, sizeof(struct value));
2475 tstamp = crypto_time();
2476 vp->tstamp = htonl(tstamp);
2477 vp->fstamp = htonl(peer->ident_pkey->fstamp);
2478 vp->vallen = htonl(len);
2479 vp->ptr = emalloc(len);
2480 BN_bn2bin(peer->iffval, vp->ptr);
2484 vp->sig = emalloc(sign_siglen);
2485 EVP_SignInit(&ctx, sign_digest);
2486 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2487 EVP_SignUpdate(&ctx, vp->ptr, len);
2488 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
2489 NTP_INSIST(len <= sign_siglen);
2490 vp->siglen = htonl(len);
2497 * crypto_bob2 - construct Bob's response to Alice's challenge
2501 * XEVNT_ERR protocol error
2502 * XEVNT_ID bad or missing group key
2506 struct exten *ep, /* extension pointer */
2507 struct value *vp /* value pointer */
2510 RSA *rsa; /* GQ parameters */
2511 DSA_SIG *sdsa; /* DSA parameters */
2512 BN_CTX *bctx; /* BIGNUM context */
2513 EVP_MD_CTX ctx; /* signature context */
2514 tstamp_t tstamp; /* NTP timestamp */
2515 BIGNUM *r, *k, *g, *y;
2521 * If the GQ parameters are not valid, something awful
2522 * happened or we are being tormented.
2524 if (gqkey_info == NULL) {
2525 msyslog(LOG_NOTICE, "crypto_bob2: scheme unavailable");
2528 rsa = gqkey_info->pkey->pkey.rsa;
2531 * Extract r from the challenge.
2533 len = ntohl(ep->vallen);
2534 if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2535 msyslog(LOG_ERR, "crypto_bob2: %s",
2536 ERR_error_string(ERR_get_error(), NULL));
2541 * Bob rolls random k (0 < k < n), computes y = k u^r mod n and
2542 * x = k^b mod n, then sends (y, hash(x)) to Alice.
2544 bctx = BN_CTX_new(); k = BN_new(); g = BN_new(); y = BN_new();
2545 sdsa = DSA_SIG_new();
2546 BN_rand(k, len * 8, -1, 1); /* k */
2547 BN_mod(k, k, rsa->n, bctx);
2548 BN_mod_exp(y, rsa->p, r, rsa->n, bctx); /* u^r mod n */
2549 BN_mod_mul(y, k, y, rsa->n, bctx); /* k u^r mod n */
2550 sdsa->r = BN_dup(y);
2551 BN_mod_exp(g, k, rsa->e, rsa->n, bctx); /* k^b mod n */
2553 sdsa->s = BN_dup(g);
2555 BN_free(r); BN_free(k); BN_free(g); BN_free(y);
2558 RSA_print_fp(stdout, rsa, 0);
2562 * Encode the values in ASN.1 and sign. The filestamp is from
2565 len = s_len = i2d_DSA_SIG(sdsa, NULL);
2567 msyslog(LOG_ERR, "crypto_bob2: %s",
2568 ERR_error_string(ERR_get_error(), NULL));
2572 memset(vp, 0, sizeof(struct value));
2573 tstamp = crypto_time();
2574 vp->tstamp = htonl(tstamp);
2575 vp->fstamp = htonl(gqkey_info->fstamp);
2576 vp->vallen = htonl(len);
2579 i2d_DSA_SIG(sdsa, &ptr);
2584 vp->sig = emalloc(sign_siglen);
2585 EVP_SignInit(&ctx, sign_digest);
2586 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2587 EVP_SignUpdate(&ctx, vp->ptr, len);
2588 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
2589 NTP_INSIST(len <= sign_siglen);
2590 vp->siglen = htonl(len);
2597 * crypto_gq - verify Bob's response to Alice's challenge
2601 * XEVNT_ERR protocol error
2602 * XEVNT_FSP bad filestamp
2603 * XEVNT_ID bad or missing group keys
2604 * XEVNT_PUB bad or missing public key
2608 struct exten *ep, /* extension pointer */
2609 struct peer *peer /* peer structure pointer */
2612 RSA *rsa; /* GQ parameters */
2613 BN_CTX *bctx; /* BIGNUM context */
2614 DSA_SIG *sdsa; /* RSA signature context fake */
2621 * If the GQ parameters are not valid or no challenge was sent,
2622 * something awful happened or we are being tormented. Note that
2623 * the filestamp on the local key file can be greater than on
2624 * the remote parameter file if the keys have been refreshed.
2626 if (peer->ident_pkey == NULL) {
2627 msyslog(LOG_NOTICE, "crypto_gq: scheme unavailable");
2630 if (ntohl(ep->fstamp) < peer->ident_pkey->fstamp) {
2631 msyslog(LOG_NOTICE, "crypto_gq: invalid filestamp %u",
2635 if ((rsa = peer->ident_pkey->pkey->pkey.rsa) == NULL) {
2636 msyslog(LOG_NOTICE, "crypto_gq: defective key");
2639 if (peer->iffval == NULL) {
2640 msyslog(LOG_NOTICE, "crypto_gq: missing challenge");
2645 * Extract the y = k u^r and hash(x = k^b) values from the
2648 bctx = BN_CTX_new(); y = BN_new(); v = BN_new();
2649 len = ntohl(ep->vallen);
2650 ptr = (u_char *)ep->pkt;
2651 if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2652 BN_CTX_free(bctx); BN_free(y); BN_free(v);
2653 msyslog(LOG_ERR, "crypto_gq: %s",
2654 ERR_error_string(ERR_get_error(), NULL));
2659 * Compute v^r y^b mod n.
2661 if (peer->grpkey == NULL) {
2662 msyslog(LOG_NOTICE, "crypto_gq: missing group key");
2665 BN_mod_exp(v, peer->grpkey, peer->iffval, rsa->n, bctx);
2667 BN_mod_exp(y, sdsa->r, rsa->e, rsa->n, bctx); /* y^b mod n */
2668 BN_mod_mul(y, v, y, rsa->n, bctx); /* v^r y^b mod n */
2671 * Verify the hash of the result matches hash(x).
2674 temp = BN_cmp(y, sdsa->s);
2675 BN_CTX_free(bctx); BN_free(y); BN_free(v);
2676 BN_free(peer->iffval);
2677 peer->iffval = NULL;
2682 msyslog(LOG_NOTICE, "crypto_gq: identity not verified");
2688 ***********************************************************************
2690 * The following routines implement the Mu-Varadharajan (MV) identity *
2693 ***********************************************************************
2695 * The Mu-Varadharajan (MV) cryptosystem was originally intended when
2696 * servers broadcast messages to clients, but clients never send
2697 * messages to servers. There is one encryption key for the server and a
2698 * separate decryption key for each client. It operated something like a
2699 * pay-per-view satellite broadcasting system where the session key is
2700 * encrypted by the broadcaster and the decryption keys are held in a
2701 * tamperproof set-top box.
2703 * The MV parameters and private encryption key hide in a DSA cuckoo
2704 * structure which uses the same parameters, but generated in a
2705 * different way. The values are used in an encryption scheme similar to
2706 * El Gamal cryptography and a polynomial formed from the expansion of
2707 * product terms (x - x[j]), as described in Mu, Y., and V.
2708 * Varadharajan: Robust and Secure Broadcasting, Proc. Indocrypt 2001,
2709 * 223-231. The paper has significant errors and serious omissions.
2711 * Let q be the product of n distinct primes s1[j] (j = 1...n), where
2712 * each s1[j] has m significant bits. Let p be a prime p = 2 * q + 1, so
2713 * that q and each s1[j] divide p - 1 and p has M = n * m + 1
2714 * significant bits. Let g be a generator of Zp; that is, gcd(g, p - 1)
2715 * = 1 and g^q = 1 mod p. We do modular arithmetic over Zq and then
2716 * project into Zp* as exponents of g. Sometimes we have to compute an
2717 * inverse b^-1 of random b in Zq, but for that purpose we require
2718 * gcd(b, q) = 1. We expect M to be in the 500-bit range and n
2719 * relatively small, like 30. These are the parameters of the scheme and
2720 * they are expensive to compute.
2722 * We set up an instance of the scheme as follows. A set of random
2723 * values x[j] mod q (j = 1...n), are generated as the zeros of a
2724 * polynomial of order n. The product terms (x - x[j]) are expanded to
2725 * form coefficients a[i] mod q (i = 0...n) in powers of x. These are
2726 * used as exponents of the generator g mod p to generate the private
2727 * encryption key A. The pair (gbar, ghat) of public server keys and the
2728 * pairs (xbar[j], xhat[j]) (j = 1...n) of private client keys are used
2729 * to construct the decryption keys. The devil is in the details.
2731 * This routine generates a private server encryption file including the
2732 * private encryption key E and partial decryption keys gbar and ghat.
2733 * It then generates public client decryption files including the public
2734 * keys xbar[j] and xhat[j] for each client j. The partial decryption
2735 * files are used to compute the inverse of E. These values are suitably
2736 * blinded so secrets are not revealed.
2738 * The distinguishing characteristic of this scheme is the capability to
2739 * revoke keys. Included in the calculation of E, gbar and ghat is the
2740 * product s = prod(s1[j]) (j = 1...n) above. If the factor s1[j] is
2741 * subsequently removed from the product and E, gbar and ghat
2742 * recomputed, the jth client will no longer be able to compute E^-1 and
2743 * thus unable to decrypt the messageblock.
2747 * The scheme goes like this. Bob has the server values (p, E, q, gbar,
2748 * ghat) and Alice has the client values (p, xbar, xhat).
2750 * Alice rolls new random nonce r mod p and sends to Bob in the MV
2751 * request message. Bob rolls random nonce k mod q, encrypts y = r E^k
2752 * mod p and sends (y, gbar^k, ghat^k) to Alice.
2754 * Alice receives the response and computes the inverse (E^k)^-1 from
2755 * the partial decryption keys gbar^k, ghat^k, xbar and xhat. She then
2756 * decrypts y and verifies it matches the original r. The signed
2757 * response binds this knowledge to Bob's private key and the public key
2758 * previously received in his certificate.
2760 * crypto_alice3 - construct Alice's challenge in MV scheme
2764 * XEVNT_ID bad or missing group key
2765 * XEVNT_PUB bad or missing public key
2769 struct peer *peer, /* peer pointer */
2770 struct value *vp /* value pointer */
2773 DSA *dsa; /* MV parameters */
2774 BN_CTX *bctx; /* BIGNUM context */
2775 EVP_MD_CTX ctx; /* signature context */
2780 * The identity parameters must have correct format and content.
2782 if (peer->ident_pkey == NULL)
2785 if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) {
2786 msyslog(LOG_NOTICE, "crypto_alice3: defective key");
2791 * Roll new random r (0 < r < q).
2793 if (peer->iffval != NULL)
2794 BN_free(peer->iffval);
2795 peer->iffval = BN_new();
2796 len = BN_num_bytes(dsa->p);
2797 BN_rand(peer->iffval, len * 8, -1, 1); /* r mod p */
2798 bctx = BN_CTX_new();
2799 BN_mod(peer->iffval, peer->iffval, dsa->p, bctx);
2803 * Sign and send to Bob. The filestamp is from the local file.
2805 memset(vp, 0, sizeof(struct value));
2806 tstamp = crypto_time();
2807 vp->tstamp = htonl(tstamp);
2808 vp->fstamp = htonl(peer->ident_pkey->fstamp);
2809 vp->vallen = htonl(len);
2810 vp->ptr = emalloc(len);
2811 BN_bn2bin(peer->iffval, vp->ptr);
2815 vp->sig = emalloc(sign_siglen);
2816 EVP_SignInit(&ctx, sign_digest);
2817 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2818 EVP_SignUpdate(&ctx, vp->ptr, len);
2819 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
2820 NTP_INSIST(len <= sign_siglen);
2821 vp->siglen = htonl(len);
2828 * crypto_bob3 - construct Bob's response to Alice's challenge
2832 * XEVNT_ERR protocol error
2836 struct exten *ep, /* extension pointer */
2837 struct value *vp /* value pointer */
2840 DSA *dsa; /* MV parameters */
2841 DSA *sdsa; /* DSA signature context fake */
2842 BN_CTX *bctx; /* BIGNUM context */
2843 EVP_MD_CTX ctx; /* signature context */
2844 tstamp_t tstamp; /* NTP timestamp */
2850 * If the MV parameters are not valid, something awful
2851 * happened or we are being tormented.
2853 if (mvkey_info == NULL) {
2854 msyslog(LOG_NOTICE, "crypto_bob3: scheme unavailable");
2857 dsa = mvkey_info->pkey->pkey.dsa;
2860 * Extract r from the challenge.
2862 len = ntohl(ep->vallen);
2863 if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2864 msyslog(LOG_ERR, "crypto_bob3: %s",
2865 ERR_error_string(ERR_get_error(), NULL));
2870 * Bob rolls random k (0 < k < q), making sure it is not a
2871 * factor of q. He then computes y = r A^k and sends (y, gbar^k,
2872 * and ghat^k) to Alice.
2874 bctx = BN_CTX_new(); k = BN_new(); u = BN_new();
2876 sdsa->p = BN_new(); sdsa->q = BN_new(); sdsa->g = BN_new();
2878 BN_rand(k, BN_num_bits(dsa->q), 0, 0);
2879 BN_mod(k, k, dsa->q, bctx);
2880 BN_gcd(u, k, dsa->q, bctx);
2884 BN_mod_exp(u, dsa->g, k, dsa->p, bctx); /* A^k r */
2885 BN_mod_mul(sdsa->p, u, r, dsa->p, bctx);
2886 BN_mod_exp(sdsa->q, dsa->priv_key, k, dsa->p, bctx); /* gbar */
2887 BN_mod_exp(sdsa->g, dsa->pub_key, k, dsa->p, bctx); /* ghat */
2888 BN_CTX_free(bctx); BN_free(k); BN_free(r); BN_free(u);
2891 DSA_print_fp(stdout, sdsa, 0);
2895 * Encode the values in ASN.1 and sign. The filestamp is from
2898 memset(vp, 0, sizeof(struct value));
2899 tstamp = crypto_time();
2900 vp->tstamp = htonl(tstamp);
2901 vp->fstamp = htonl(mvkey_info->fstamp);
2902 len = i2d_DSAparams(sdsa, NULL);
2904 msyslog(LOG_ERR, "crypto_bob3: %s",
2905 ERR_error_string(ERR_get_error(), NULL));
2909 vp->vallen = htonl(len);
2912 i2d_DSAparams(sdsa, &ptr);
2917 vp->sig = emalloc(sign_siglen);
2918 EVP_SignInit(&ctx, sign_digest);
2919 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2920 EVP_SignUpdate(&ctx, vp->ptr, len);
2921 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
2922 NTP_INSIST(len <= sign_siglen);
2923 vp->siglen = htonl(len);
2930 * crypto_mv - verify Bob's response to Alice's challenge
2934 * XEVNT_ERR protocol error
2935 * XEVNT_FSP bad filestamp
2936 * XEVNT_ID bad or missing group key
2937 * XEVNT_PUB bad or missing public key
2941 struct exten *ep, /* extension pointer */
2942 struct peer *peer /* peer structure pointer */
2945 DSA *dsa; /* MV parameters */
2946 DSA *sdsa; /* DSA parameters */
2947 BN_CTX *bctx; /* BIGNUM context */
2954 * If the MV parameters are not valid or no challenge was sent,
2955 * something awful happened or we are being tormented.
2957 if (peer->ident_pkey == NULL) {
2958 msyslog(LOG_NOTICE, "crypto_mv: scheme unavailable");
2961 if (ntohl(ep->fstamp) != peer->ident_pkey->fstamp) {
2962 msyslog(LOG_NOTICE, "crypto_mv: invalid filestamp %u",
2966 if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) {
2967 msyslog(LOG_NOTICE, "crypto_mv: defective key");
2970 if (peer->iffval == NULL) {
2971 msyslog(LOG_NOTICE, "crypto_mv: missing challenge");
2976 * Extract the y, gbar and ghat values from the response.
2978 bctx = BN_CTX_new(); k = BN_new(); u = BN_new(); v = BN_new();
2979 len = ntohl(ep->vallen);
2980 ptr = (u_char *)ep->pkt;
2981 if ((sdsa = d2i_DSAparams(NULL, &ptr, len)) == NULL) {
2982 msyslog(LOG_ERR, "crypto_mv: %s",
2983 ERR_error_string(ERR_get_error(), NULL));
2988 * Compute (gbar^xhat ghat^xbar) mod p.
2990 BN_mod_exp(u, sdsa->q, dsa->pub_key, dsa->p, bctx);
2991 BN_mod_exp(v, sdsa->g, dsa->priv_key, dsa->p, bctx);
2992 BN_mod_mul(u, u, v, dsa->p, bctx);
2993 BN_mod_mul(u, u, sdsa->p, dsa->p, bctx);
2996 * The result should match r.
2998 temp = BN_cmp(u, peer->iffval);
2999 BN_CTX_free(bctx); BN_free(k); BN_free(u); BN_free(v);
3000 BN_free(peer->iffval);
3001 peer->iffval = NULL;
3006 msyslog(LOG_NOTICE, "crypto_mv: identity not verified");
3012 ***********************************************************************
3014 * The following routines are used to manipulate certificates *
3016 ***********************************************************************
3019 * cert_sign - sign x509 certificate equest and update value structure.
3021 * The certificate request includes a copy of the host certificate,
3022 * which includes the version number, subject name and public key of the
3023 * host. The resulting certificate includes these values plus the
3024 * serial number, issuer name and valid interval of the server. The
3025 * valid interval extends from the current time to the same time one
3026 * year hence. This may extend the life of the signed certificate beyond
3027 * that of the signer certificate.
3029 * It is convenient to use the NTP seconds of the current time as the
3030 * serial number. In the value structure the timestamp is the current
3031 * time and the filestamp is taken from the extension field. Note this
3032 * routine is called only when the client clock is synchronized to a
3033 * proventic source, so timestamp comparisons are valid.
3035 * The host certificate is valid from the time it was generated for a
3036 * period of one year. A signed certificate is valid from the time of
3037 * signature for a period of one year, but only the host certificate (or
3038 * sign certificate if used) is actually used to encrypt and decrypt
3039 * signatures. The signature trail is built from the client via the
3040 * intermediate servers to the trusted server. Each signature on the
3041 * trail must be valid at the time of signature, but it could happen
3042 * that a signer certificate expire before the signed certificate, which
3043 * remains valid until its expiration.
3047 * XEVNT_CRT bad or missing certificate
3048 * XEVNT_PER host certificate expired
3049 * XEVNT_PUB bad or missing public key
3050 * XEVNT_VFY certificate not verified
3054 struct exten *ep, /* extension field pointer */
3055 struct value *vp /* value pointer */
3058 X509 *req; /* X509 certificate request */
3059 X509 *cert; /* X509 certificate */
3060 X509_EXTENSION *ext; /* certificate extension */
3061 ASN1_INTEGER *serial; /* serial number */
3062 X509_NAME *subj; /* distinguished (common) name */
3063 EVP_PKEY *pkey; /* public key */
3064 EVP_MD_CTX ctx; /* message digest context */
3065 tstamp_t tstamp; /* NTP timestamp */
3066 struct calendar tscal;
3073 * Decode ASN.1 objects and construct certificate structure.
3074 * Make sure the system clock is synchronized to a proventic
3077 tstamp = crypto_time();
3081 cptr = (void *)ep->pkt;
3082 if ((req = d2i_X509(NULL, &cptr, ntohl(ep->vallen))) == NULL) {
3083 msyslog(LOG_ERR, "cert_sign: %s",
3084 ERR_error_string(ERR_get_error(), NULL));
3088 * Extract public key and check for errors.
3090 if ((pkey = X509_get_pubkey(req)) == NULL) {
3091 msyslog(LOG_ERR, "cert_sign: %s",
3092 ERR_error_string(ERR_get_error(), NULL));
3098 * Generate X509 certificate signed by this server. If this is a
3099 * trusted host, the issuer name is the group name; otherwise,
3100 * it is the host name. Also copy any extensions that might be
3104 X509_set_version(cert, X509_get_version(req));
3105 serial = ASN1_INTEGER_new();
3106 ASN1_INTEGER_set(serial, tstamp);
3107 X509_set_serialNumber(cert, serial);
3108 X509_gmtime_adj(X509_get_notBefore(cert), 0L);
3109 X509_gmtime_adj(X509_get_notAfter(cert), YEAR);
3110 subj = X509_get_issuer_name(cert);
3111 X509_NAME_add_entry_by_txt(subj, "commonName", MBSTRING_ASC,
3112 hostval.ptr, strlen((const char *)hostval.ptr), -1, 0);
3113 subj = X509_get_subject_name(req);
3114 X509_set_subject_name(cert, subj);
3115 X509_set_pubkey(cert, pkey);
3116 temp = X509_get_ext_count(req);
3117 for (i = 0; i < temp; i++) {
3118 ext = X509_get_ext(req, i);
3119 INSIST(X509_add_ext(cert, ext, -1));
3124 * Sign and verify the client certificate, but only if the host
3125 * certificate has not expired.
3127 (void)ntpcal_ntp_to_date(&tscal, tstamp, NULL);
3128 if ((calcomp(&tscal, &(cert_host->first)) < 0)
3129 || (calcomp(&tscal, &(cert_host->last)) > 0)) {
3133 X509_sign(cert, sign_pkey, sign_digest);
3134 if (X509_verify(cert, sign_pkey) <= 0) {
3135 msyslog(LOG_ERR, "cert_sign: %s",
3136 ERR_error_string(ERR_get_error(), NULL));
3140 len = i2d_X509(cert, NULL);
3143 * Build and sign the value structure. We have to sign it here,
3144 * since the response has to be returned right away. This is a
3147 memset(vp, 0, sizeof(struct value));
3148 vp->tstamp = htonl(tstamp);
3149 vp->fstamp = ep->fstamp;
3150 vp->vallen = htonl(len);
3151 vp->ptr = emalloc(len);
3153 i2d_X509(cert, (unsigned char **)(intptr_t)&ptr);
3156 vp->sig = emalloc(sign_siglen);
3157 EVP_SignInit(&ctx, sign_digest);
3158 EVP_SignUpdate(&ctx, (u_char *)vp, 12);
3159 EVP_SignUpdate(&ctx, vp->ptr, len);
3160 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey)) {
3161 NTP_INSIST(len <= sign_siglen);
3162 vp->siglen = htonl(len);
3167 X509_print_fp(stdout, cert);
3175 * cert_install - install certificate in certificate cache
3177 * This routine encodes an extension field into a certificate info/value
3178 * structure. It searches the certificate list for duplicates and
3179 * expunges whichever is older. Finally, it inserts this certificate
3180 * first on the list.
3182 * Returns certificate info pointer if valid, NULL if not.
3186 struct exten *ep, /* cert info/value */
3187 struct peer *peer /* peer structure */
3190 struct cert_info *cp, *xp, **zp;
3193 * Parse and validate the signed certificate. If valid,
3194 * construct the info/value structure; otherwise, scamper home
3197 if ((cp = cert_parse((u_char *)ep->pkt, (long)ntohl(ep->vallen),
3198 (tstamp_t)ntohl(ep->fstamp))) == NULL)
3202 * Scan certificate list looking for another certificate with
3203 * the same subject and issuer. If another is found with the
3204 * same or older filestamp, unlink it and return the goodies to
3205 * the heap. If another is found with a later filestamp, discard
3206 * the new one and leave the building with the old one.
3208 * Make a note to study this issue again. An earlier certificate
3209 * with a long lifetime might be overtaken by a later
3210 * certificate with a short lifetime, thus invalidating the
3211 * earlier signature. However, we gotta find a way to leak old
3212 * stuff from the cache, so we do it anyway.
3215 for (xp = cinfo; xp != NULL; xp = xp->link) {
3216 if (strcmp(cp->subject, xp->subject) == 0 &&
3217 strcmp(cp->issuer, xp->issuer) == 0) {
3218 if (ntohl(cp->cert.fstamp) <=
3219 ntohl(xp->cert.fstamp)) {
3235 cp->flags |= CERT_VALID;
3242 * cert_hike - verify the signature using the issuer public key
3246 * XEVNT_CRT bad or missing certificate
3247 * XEVNT_PER host certificate expired
3248 * XEVNT_VFY certificate not verified
3252 struct peer *peer, /* peer structure pointer */
3253 struct cert_info *yp /* issuer certificate */
3256 struct cert_info *xp; /* subject certificate */
3257 X509 *cert; /* X509 certificate */
3261 * Save the issuer on the new certificate, but remember the old
3264 if (peer->issuer != NULL)
3266 peer->issuer = estrdup(yp->issuer);
3271 * If subject Y matches issuer Y, then the certificate trail is
3272 * complete. If Y is not trusted, the server certificate has yet
3273 * been signed, so keep trying. Otherwise, save the group key
3274 * and light the valid bit. If the host certificate is trusted,
3275 * do not execute a sign exchange. If no identity scheme is in
3276 * use, light the identity and proventic bits.
3278 if (strcmp(yp->subject, yp->issuer) == 0) {
3279 if (!(yp->flags & CERT_TRUST))
3283 * If the server has an an identity scheme, fetch the
3284 * identity credentials. If not, the identity is
3285 * verified only by the trusted certificate. The next
3286 * signature will set the server proventic.
3288 peer->crypto |= CRYPTO_FLAG_CERT;
3289 peer->grpkey = yp->grpkey;
3290 if (peer->ident == NULL || !(peer->crypto &
3292 peer->crypto |= CRYPTO_FLAG_VRFY;
3296 * If X exists, verify signature X using public key Y.
3301 ptr = (u_char *)xp->cert.ptr;
3302 cert = d2i_X509(NULL, &ptr, ntohl(xp->cert.vallen));
3304 xp->flags |= CERT_ERROR;
3307 if (X509_verify(cert, yp->pkey) <= 0) {
3309 xp->flags |= CERT_ERROR;
3315 * Signature X is valid only if it begins during the
3318 if ((calcomp(&(xp->first), &(yp->first)) < 0)
3319 || (calcomp(&(xp->first), &(yp->last)) > 0)) {
3320 xp->flags |= CERT_ERROR;
3323 xp->flags |= CERT_SIGN;
3329 * cert_parse - parse x509 certificate and create info/value structures.
3331 * The server certificate includes the version number, issuer name,
3332 * subject name, public key and valid date interval. If the issuer name
3333 * is the same as the subject name, the certificate is self signed and
3334 * valid only if the server is configured as trustable. If the names are
3335 * different, another issuer has signed the server certificate and
3336 * vouched for it. In this case the server certificate is valid if
3337 * verified by the issuer public key.
3339 * Returns certificate info/value pointer if valid, NULL if not.
3341 struct cert_info * /* certificate information structure */
3343 const u_char *asn1cert, /* X509 certificate */
3344 long len, /* certificate length */
3345 tstamp_t fstamp /* filestamp */
3348 X509 *cert; /* X509 certificate */
3349 X509_EXTENSION *ext; /* X509v3 extension */
3350 struct cert_info *ret; /* certificate info/value */
3352 char pathbuf[MAXFILENAME];
3356 struct calendar fscal;
3359 * Decode ASN.1 objects and construct certificate structure.
3362 if ((cert = d2i_X509(NULL, &ptr, len)) == NULL) {
3363 msyslog(LOG_ERR, "cert_parse: %s",
3364 ERR_error_string(ERR_get_error(), NULL));
3369 X509_print_fp(stdout, cert);
3373 * Extract version, subject name and public key.
3375 ret = emalloc_zero(sizeof(*ret));
3376 if ((ret->pkey = X509_get_pubkey(cert)) == NULL) {
3377 msyslog(LOG_ERR, "cert_parse: %s",
3378 ERR_error_string(ERR_get_error(), NULL));
3383 ret->version = X509_get_version(cert);
3384 X509_NAME_oneline(X509_get_subject_name(cert), pathbuf,
3386 pch = strstr(pathbuf, "CN=");
3388 msyslog(LOG_NOTICE, "cert_parse: invalid subject %s",
3394 ret->subject = estrdup(pch + 3);
3397 * Extract remaining objects. Note that the NTP serial number is
3398 * the NTP seconds at the time of signing, but this might not be
3399 * the case for other authority. We don't bother to check the
3400 * objects at this time, since the real crunch can happen only
3401 * when the time is valid but not yet certificated.
3403 ret->nid = OBJ_obj2nid(cert->cert_info->signature->algorithm);
3404 ret->digest = (const EVP_MD *)EVP_get_digestbynid(ret->nid);
3406 (u_long)ASN1_INTEGER_get(X509_get_serialNumber(cert));
3407 X509_NAME_oneline(X509_get_issuer_name(cert), pathbuf,
3409 if ((pch = strstr(pathbuf, "CN=")) == NULL) {
3410 msyslog(LOG_NOTICE, "cert_parse: invalid issuer %s",
3416 ret->issuer = estrdup(pch + 3);
3417 asn_to_calendar(X509_get_notBefore(cert), &(ret->first));
3418 asn_to_calendar(X509_get_notAfter(cert), &(ret->last));
3421 * Extract extension fields. These are ad hoc ripoffs of
3422 * currently assigned functions and will certainly be changed
3423 * before prime time.
3425 cnt = X509_get_ext_count(cert);
3426 for (i = 0; i < cnt; i++) {
3427 ext = X509_get_ext(cert, i);
3428 temp = OBJ_obj2nid(ext->object);
3432 * If a key_usage field is present, we decode whether
3433 * this is a trusted or private certificate. This is
3434 * dorky; all we want is to compare NIDs, but OpenSSL
3435 * insists on BIO text strings.
3437 case NID_ext_key_usage:
3438 bp = BIO_new(BIO_s_mem());
3439 X509V3_EXT_print(bp, ext, 0, 0);
3440 BIO_gets(bp, pathbuf, sizeof(pathbuf));
3442 if (strcmp(pathbuf, "Trust Root") == 0)
3443 ret->flags |= CERT_TRUST;
3444 else if (strcmp(pathbuf, "Private") == 0)
3445 ret->flags |= CERT_PRIV;
3446 DPRINTF(1, ("cert_parse: %s: %s\n",
3447 OBJ_nid2ln(temp), pathbuf));
3451 * If a NID_subject_key_identifier field is present, it
3452 * contains the GQ public key.
3454 case NID_subject_key_identifier:
3455 ret->grpkey = BN_bin2bn(&ext->value->data[2],
3456 ext->value->length - 2, NULL);
3459 DPRINTF(1, ("cert_parse: %s\n",
3464 if (strcmp(ret->subject, ret->issuer) == 0) {
3467 * If certificate is self signed, verify signature.
3469 if (X509_verify(cert, ret->pkey) <= 0) {
3471 "cert_parse: signature not verified %s",
3480 * Check for a certificate loop.
3482 if (strcmp((const char *)hostval.ptr, ret->issuer) == 0) {
3484 "cert_parse: certificate trail loop %s",
3493 * Verify certificate valid times. Note that certificates cannot
3496 (void)ntpcal_ntp_to_date(&fscal, fstamp, NULL);
3497 if ((calcomp(&(ret->first), &(ret->last)) > 0)
3498 || (calcomp(&(ret->first), &fscal) < 0)) {
3500 "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",
3502 ret->first.year, ret->first.month, ret->first.monthday,
3503 ret->first.hour, ret->first.minute, ret->first.second,
3504 ret->last.year, ret->last.month, ret->last.monthday,
3505 ret->last.hour, ret->last.minute, ret->last.second,
3506 fscal.year, fscal.month, fscal.monthday,
3507 fscal.hour, fscal.minute, fscal.second);
3514 * Build the value structure to sign and send later.
3516 ret->cert.fstamp = htonl(fstamp);
3517 ret->cert.vallen = htonl(len);
3518 ret->cert.ptr = emalloc(len);
3519 memcpy(ret->cert.ptr, asn1cert, len);
3526 * cert_free - free certificate information structure
3530 struct cert_info *cinf /* certificate info/value structure */
3533 if (cinf->pkey != NULL)
3534 EVP_PKEY_free(cinf->pkey);
3535 if (cinf->subject != NULL)
3536 free(cinf->subject);
3537 if (cinf->issuer != NULL)
3539 if (cinf->grpkey != NULL)
3540 BN_free(cinf->grpkey);
3541 value_free(&cinf->cert);
3547 * crypto_key - load cryptographic parameters and keys
3549 * This routine searches the key cache for matching name in the form
3550 * ntpkey_<key>_<name>, where <key> is one of host, sign, iff, gq, mv,
3551 * and <name> is the host/group name. If not found, it tries to load a
3552 * PEM-encoded file of the same name and extracts the filestamp from
3553 * the first line of the file name. It returns the key pointer if valid,
3556 static struct pkey_info *
3558 char *cp, /* file name */
3559 char *passwd1, /* password */
3560 sockaddr_u *addr /* IP address */
3563 FILE *str; /* file handle */
3564 struct pkey_info *pkp; /* generic key */
3565 EVP_PKEY *pkey = NULL; /* public/private key */
3567 char filename[MAXFILENAME]; /* name of key file */
3568 char linkname[MAXFILENAME]; /* filestamp buffer) */
3569 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3573 * Search the key cache for matching key and name.
3575 for (pkp = pkinfo; pkp != NULL; pkp = pkp->link) {
3576 if (strcmp(cp, pkp->name) == 0)
3581 * Open the key file. If the first character of the file name is
3582 * not '/', prepend the keys directory string. If something goes
3583 * wrong, abandon ship.
3586 strlcpy(filename, cp, sizeof(filename));
3588 snprintf(filename, sizeof(filename), "%s/%s", keysdir,
3590 str = fopen(filename, "r");
3595 * Read the filestamp, which is contained in the first line.
3597 if ((ptr = fgets(linkname, sizeof(linkname), str)) == NULL) {
3598 msyslog(LOG_ERR, "crypto_key: empty file %s",
3603 if ((ptr = strrchr(ptr, '.')) == NULL) {
3604 msyslog(LOG_ERR, "crypto_key: no filestamp %s",
3609 if (sscanf(++ptr, "%u", &fstamp) != 1) {
3610 msyslog(LOG_ERR, "crypto_key: invalid filestamp %s",
3617 * Read and decrypt PEM-encoded private key. If it fails to
3618 * decrypt, game over.
3620 pkey = PEM_read_PrivateKey(str, NULL, NULL, passwd1);
3623 msyslog(LOG_ERR, "crypto_key: %s",
3624 ERR_error_string(ERR_get_error(), NULL));
3629 * Make a new entry in the key cache.
3631 pkp = emalloc(sizeof(struct pkey_info));
3635 pkp->name = estrdup(cp);
3636 pkp->fstamp = fstamp;
3639 * Leave tracks in the cryptostats.
3641 if ((ptr = strrchr(linkname, '\n')) != NULL)
3643 snprintf(statstr, sizeof(statstr), "%s mod %d", &linkname[2],
3644 EVP_PKEY_size(pkey) * 8);
3645 record_crypto_stats(addr, statstr);
3647 DPRINTF(1, ("crypto_key: %s\n", statstr));
3650 if (pkey->type == EVP_PKEY_DSA)
3651 DSA_print_fp(stdout, pkey->pkey.dsa, 0);
3652 else if (pkey->type == EVP_PKEY_RSA)
3653 RSA_print_fp(stdout, pkey->pkey.rsa, 0);
3661 ***********************************************************************
3663 * The following routines are used only at initialization time *
3665 ***********************************************************************
3668 * crypto_cert - load certificate from file
3670 * This routine loads an X.509 RSA or DSA certificate from a file and
3671 * constructs a info/cert value structure for this machine. The
3672 * structure includes a filestamp extracted from the file name. Later
3673 * the certificate can be sent to another machine on request.
3675 * Returns certificate info/value pointer if valid, NULL if not.
3677 static struct cert_info * /* certificate information */
3679 char *cp /* file name */
3682 struct cert_info *ret; /* certificate information */
3683 FILE *str; /* file handle */
3684 char filename[MAXFILENAME]; /* name of certificate file */
3685 char linkname[MAXFILENAME]; /* filestamp buffer */
3686 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3687 tstamp_t fstamp; /* filestamp */
3690 char *name, *header;
3694 * Open the certificate file. If the first character of the file
3695 * name is not '/', prepend the keys directory string. If
3696 * something goes wrong, abandon ship.
3699 strlcpy(filename, cp, sizeof(filename));
3701 snprintf(filename, sizeof(filename), "%s/%s", keysdir,
3703 str = fopen(filename, "r");
3708 * Read the filestamp, which is contained in the first line.
3710 if ((ptr = fgets(linkname, sizeof(linkname), str)) == NULL) {
3711 msyslog(LOG_ERR, "crypto_cert: empty file %s",
3716 if ((ptr = strrchr(ptr, '.')) == NULL) {
3717 msyslog(LOG_ERR, "crypto_cert: no filestamp %s",
3722 if (sscanf(++ptr, "%u", &fstamp) != 1) {
3723 msyslog(LOG_ERR, "crypto_cert: invalid filestamp %s",
3730 * Read PEM-encoded certificate and install.
3732 if (!PEM_read(str, &name, &header, &data, &len)) {
3733 msyslog(LOG_ERR, "crypto_cert: %s",
3734 ERR_error_string(ERR_get_error(), NULL));
3740 if (strcmp(name, "CERTIFICATE") != 0) {
3741 msyslog(LOG_NOTICE, "crypto_cert: wrong PEM type %s",
3750 * Parse certificate and generate info/value structure. The
3751 * pointer and copy nonsense is due something broken in Solaris.
3753 ret = cert_parse(data, len, fstamp);
3758 if ((ptr = strrchr(linkname, '\n')) != NULL)
3760 snprintf(statstr, sizeof(statstr), "%s 0x%x len %lu",
3761 &linkname[2], ret->flags, len);
3762 record_crypto_stats(NULL, statstr);
3763 DPRINTF(1, ("crypto_cert: %s\n", statstr));
3769 * crypto_setup - load keys, certificate and identity parameters
3771 * This routine loads the public/private host key and certificate. If
3772 * available, it loads the public/private sign key, which defaults to
3773 * the host key. The host key must be RSA, but the sign key can be
3774 * either RSA or DSA. If a trusted certificate, it loads the identity
3775 * parameters. In either case, the public key on the certificate must
3776 * agree with the sign key.
3778 * Required but missing files and inconsistent data and errors are
3779 * fatal. Allowing configuration to continue would be hazardous and
3780 * require really messy error checks.
3785 struct pkey_info *pinfo; /* private/public key */
3786 char filename[MAXFILENAME]; /* file name buffer */
3787 char hostname[MAXFILENAME]; /* host name buffer */
3789 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3790 l_fp seed; /* crypto PRNG seed as NTP timestamp */
3796 * Check for correct OpenSSL version and avoid initialization in
3797 * the case of multiple crypto commands.
3799 if (crypto_flags & CRYPTO_FLAG_ENAB) {
3801 "crypto_setup: spurious crypto command");
3804 ssl_check_version();
3807 * Load required random seed file and seed the random number
3808 * generator. Be default, it is found as .rnd in the user home
3809 * directory. The root home directory may be / or /root,
3810 * depending on the system. Wiggle the contents a bit and write
3811 * it back so the sequence does not repeat when we next restart.
3813 if (!RAND_status()) {
3814 if (rand_file == NULL) {
3815 RAND_file_name(filename, sizeof(filename));
3816 randfile = filename;
3817 } else if (*rand_file != '/') {
3818 snprintf(filename, sizeof(filename), "%s/%s",
3819 keysdir, rand_file);
3820 randfile = filename;
3822 randfile = rand_file;
3824 if ((bytes = RAND_load_file(randfile, -1)) == 0) {
3826 "crypto_setup: random seed file %s missing",
3830 arc4random_buf(&seed, sizeof(l_fp));
3831 RAND_seed(&seed, sizeof(l_fp));
3832 RAND_write_file(randfile);
3833 DPRINTF(1, ("crypto_setup: OpenSSL version %lx random seed file %s bytes read %d\n",
3834 SSLeay(), randfile, bytes));
3838 * Initialize structures.
3840 gethostname(hostname, sizeof(hostname));
3841 if (host_filename != NULL)
3842 strlcpy(hostname, host_filename, sizeof(hostname));
3844 passwd = estrdup(hostname);
3845 memset(&hostval, 0, sizeof(hostval));
3846 memset(&pubkey, 0, sizeof(pubkey));
3847 memset(&tai_leap, 0, sizeof(tai_leap));
3850 * Load required host key from file "ntpkey_host_<hostname>". If
3851 * no host key file is not found or has invalid password, life
3852 * as we know it ends. The host key also becomes the default
3855 snprintf(filename, sizeof(filename), "ntpkey_host_%s", hostname);
3856 pinfo = crypto_key(filename, passwd, NULL);
3857 if (pinfo == NULL) {
3859 "crypto_setup: host key file %s not found or corrupt",
3863 if (pinfo->pkey->type != EVP_PKEY_RSA) {
3865 "crypto_setup: host key is not RSA key type");
3868 host_pkey = pinfo->pkey;
3869 sign_pkey = host_pkey;
3870 hostval.fstamp = htonl(pinfo->fstamp);
3873 * Construct public key extension field for agreement scheme.
3875 len = i2d_PublicKey(host_pkey, NULL);
3878 i2d_PublicKey(host_pkey, &ptr);
3879 pubkey.fstamp = hostval.fstamp;
3880 pubkey.vallen = htonl(len);
3883 * Load optional sign key from file "ntpkey_sign_<hostname>". If
3884 * available, it becomes the sign key.
3886 snprintf(filename, sizeof(filename), "ntpkey_sign_%s", hostname);
3887 pinfo = crypto_key(filename, passwd, NULL);
3889 sign_pkey = pinfo->pkey;
3892 * Load required certificate from file "ntpkey_cert_<hostname>".
3894 snprintf(filename, sizeof(filename), "ntpkey_cert_%s", hostname);
3895 cinfo = crypto_cert(filename);
3896 if (cinfo == NULL) {
3898 "crypto_setup: certificate file %s not found or corrupt",
3903 sign_digest = cinfo->digest;
3904 sign_siglen = EVP_PKEY_size(sign_pkey);
3905 if (cinfo->flags & CERT_PRIV)
3906 crypto_flags |= CRYPTO_FLAG_PRIV;
3909 * The certificate must be self-signed.
3911 if (strcmp(cinfo->subject, cinfo->issuer) != 0) {
3913 "crypto_setup: certificate %s is not self-signed",
3917 hostval.ptr = estrdup(cinfo->subject);
3918 hostval.vallen = htonl(strlen(cinfo->subject));
3919 sys_hostname = hostval.ptr;
3920 ptr = (u_char *)strchr(sys_hostname, '@');
3922 sys_groupname = estrdup((char *)++ptr);
3923 if (ident_filename != NULL)
3924 strlcpy(hostname, ident_filename, sizeof(hostname));
3927 * Load optional IFF parameters from file
3928 * "ntpkey_iffkey_<hostname>".
3930 snprintf(filename, sizeof(filename), "ntpkey_iffkey_%s",
3932 iffkey_info = crypto_key(filename, passwd, NULL);
3933 if (iffkey_info != NULL)
3934 crypto_flags |= CRYPTO_FLAG_IFF;
3937 * Load optional GQ parameters from file
3938 * "ntpkey_gqkey_<hostname>".
3940 snprintf(filename, sizeof(filename), "ntpkey_gqkey_%s",
3942 gqkey_info = crypto_key(filename, passwd, NULL);
3943 if (gqkey_info != NULL)
3944 crypto_flags |= CRYPTO_FLAG_GQ;
3947 * Load optional MV parameters from file
3948 * "ntpkey_mvkey_<hostname>".
3950 snprintf(filename, sizeof(filename), "ntpkey_mvkey_%s",
3952 mvkey_info = crypto_key(filename, passwd, NULL);
3953 if (mvkey_info != NULL)
3954 crypto_flags |= CRYPTO_FLAG_MV;
3957 * We met the enemy and he is us. Now strike up the dance.
3959 crypto_flags |= CRYPTO_FLAG_ENAB | (cinfo->nid << 16);
3960 snprintf(statstr, sizeof(statstr), "setup 0x%x host %s %s",
3961 crypto_flags, hostname, OBJ_nid2ln(cinfo->nid));
3962 record_crypto_stats(NULL, statstr);
3963 DPRINTF(1, ("crypto_setup: %s\n", statstr));
3968 * crypto_config - configure data from the crypto command.
3972 int item, /* configuration item */
3973 char *cp /* item name */
3978 DPRINTF(1, ("crypto_config: item %d %s\n", item, cp));
3983 * Set host name (host).
3985 case CRYPTO_CONF_PRIV:
3986 if (NULL != host_filename)
3987 free(host_filename);
3988 host_filename = estrdup(cp);
3992 * Set group name (ident).
3994 case CRYPTO_CONF_IDENT:
3995 if (NULL != ident_filename)
3996 free(ident_filename);
3997 ident_filename = estrdup(cp);
4001 * Set private key password (pw).
4003 case CRYPTO_CONF_PW:
4006 passwd = estrdup(cp);
4010 * Set random seed file name (randfile).
4012 case CRYPTO_CONF_RAND:
4013 if (NULL != rand_file)
4015 rand_file = estrdup(cp);
4019 * Set message digest NID.
4021 case CRYPTO_CONF_NID:
4022 nid = OBJ_sn2nid(cp);
4025 "crypto_config: invalid digest name %s", cp);
4031 # else /* !AUTOKEY follows */
4032 int ntp_crypto_bs_pubkey;
4033 # endif /* !AUTOKEY */