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 = emalloc(sizeof(keyid_t) *
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 vp->siglen = htonl(sign_siglen);
384 peer->flags |= FLAG_ASSOC;
389 printf("make_keys: %d %08x %08x ts %u fs %u poll %d\n",
390 peer->keynumber, keyid, cookie, ntohl(vp->tstamp),
391 ntohl(vp->fstamp), peer->hpoll);
398 * crypto_recv - parse extension fields
400 * This routine is called when the packet has been matched to an
401 * association and passed sanity, format and MAC checks. We believe the
402 * extension field values only if the field has proper format and
403 * length, the timestamp and filestamp are valid and the signature has
404 * valid length and is verified. There are a few cases where some values
405 * are believed even if the signature fails, but only if the proventic
410 * XEVNT_ERR protocol error
411 * XEVNT_LEN bad field format or length
415 struct peer *peer, /* peer structure pointer */
416 struct recvbuf *rbufp /* packet buffer pointer */
419 const EVP_MD *dp; /* message digest algorithm */
420 u_int32 *pkt; /* receive packet pointer */
421 struct autokey *ap, *bp; /* autokey pointer */
422 struct exten *ep, *fp; /* extension pointers */
423 struct cert_info *xinfo; /* certificate info pointer */
424 int has_mac; /* length of MAC field */
425 int authlen; /* offset of MAC field */
426 associd_t associd; /* association ID */
427 tstamp_t fstamp = 0; /* filestamp */
428 u_int len; /* extension field length */
429 u_int code; /* extension field opcode */
430 u_int vallen = 0; /* value length */
431 X509 *cert; /* X509 certificate */
432 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
433 keyid_t cookie; /* crumbles */
434 int hismode; /* packet mode */
440 * Initialize. Note that the packet has already been checked for
441 * valid format and extension field lengths. First extract the
442 * field length, command code and association ID in host byte
443 * order. These are used with all commands and modes. Then check
444 * the version number, which must be 2, and length, which must
445 * be at least 8 for requests and VALUE_LEN (24) for responses.
446 * Packets that fail either test sink without a trace. The
447 * association ID is saved only if nonzero.
449 authlen = LEN_PKT_NOMAC;
450 hismode = (int)PKT_MODE((&rbufp->recv_pkt)->li_vn_mode);
451 while ((has_mac = rbufp->recv_length - authlen) > (int)MAX_MAC_LEN) {
452 pkt = (u_int32 *)&rbufp->recv_pkt + authlen / 4;
453 ep = (struct exten *)pkt;
454 code = ntohl(ep->opcode) & 0xffff0000;
455 len = ntohl(ep->opcode) & 0x0000ffff;
456 // HMS: Why pkt[1] instead of ep->associd ?
457 associd = (associd_t)ntohl(pkt[1]);
462 "crypto_recv: flags 0x%x ext offset %d len %u code 0x%x associd %d\n",
463 peer->crypto, authlen, len, code >> 16,
468 * Check version number and field length. If bad,
469 * quietly ignore the packet.
471 if (((code >> 24) & 0x3f) != CRYPTO_VN || len < 8) {
473 code |= CRYPTO_ERROR;
476 if (len >= VALUE_LEN) {
477 fstamp = ntohl(ep->fstamp);
478 vallen = ntohl(ep->vallen);
480 * Bug 2761: I hope this isn't too early...
483 || len - VALUE_LEN < vallen)
489 * Install status word, host name, signature scheme and
490 * association ID. In OpenSSL the signature algorithm is
491 * bound to the digest algorithm, so the NID completely
492 * defines the signature scheme. Note the request and
493 * response are identical, but neither is validated by
494 * signature. The request is processed here only in
495 * symmetric modes. The server name field might be
496 * useful to implement access controls in future.
501 * If our state machine is running when this
502 * message arrives, the other fellow might have
503 * restarted. However, this could be an
504 * intruder, so just clamp the poll interval and
505 * find out for ourselves. Otherwise, pass the
506 * extension field to the transmit side.
508 if (peer->crypto & CRYPTO_FLAG_CERT) {
513 if (peer->assoc != associd) {
520 fp->associd = htonl(peer->associd);
524 case CRYPTO_ASSOC | CRYPTO_RESP:
527 * Discard the message if it has already been
528 * stored or the message has been amputated.
531 if (peer->assoc != associd)
535 INSIST(len >= VALUE_LEN);
536 if (vallen == 0 || vallen > MAXHOSTNAME ||
537 len - VALUE_LEN < vallen) {
544 "crypto_recv: ident host 0x%x %d server 0x%x %d\n",
545 crypto_flags, peer->associd, fstamp,
548 temp32 = crypto_flags & CRYPTO_FLAG_MASK;
551 * If the client scheme is PC, the server scheme
552 * must be PC. The public key and identity are
553 * presumed valid, so we skip the certificate
554 * and identity exchanges and move immediately
555 * to the cookie exchange which confirms the
558 if (crypto_flags & CRYPTO_FLAG_PRIV) {
559 if (!(fstamp & CRYPTO_FLAG_PRIV)) {
563 fstamp |= CRYPTO_FLAG_CERT |
564 CRYPTO_FLAG_VRFY | CRYPTO_FLAG_SIGN;
567 * It is an error if either peer supports
568 * identity, but the other does not.
570 } else if (hismode == MODE_ACTIVE || hismode ==
572 if ((temp32 && !(fstamp &
573 CRYPTO_FLAG_MASK)) ||
574 (!temp32 && (fstamp &
575 CRYPTO_FLAG_MASK))) {
582 * Discard the message if the signature digest
583 * NID is not supported.
585 temp32 = (fstamp >> 16) & 0xffff;
587 (const EVP_MD *)EVP_get_digestbynid(temp32);
594 * Save status word, host name and message
595 * digest/signature type. If this is from a
596 * broadcast and the association ID has changed,
597 * request the autokey values.
599 peer->assoc = associd;
600 if (hismode == MODE_SERVER)
601 fstamp |= CRYPTO_FLAG_AUTO;
602 if (!(fstamp & CRYPTO_FLAG_TAI))
603 fstamp |= CRYPTO_FLAG_LEAP;
604 RAND_bytes((u_char *)&peer->hcookie, 4);
605 peer->crypto = fstamp;
607 if (peer->subject != NULL)
609 peer->subject = emalloc(vallen + 1);
610 memcpy(peer->subject, ep->pkt, vallen);
611 peer->subject[vallen] = '\0';
612 if (peer->issuer != NULL)
614 peer->issuer = estrdup(peer->subject);
615 snprintf(statstr, sizeof(statstr),
616 "assoc %d %d host %s %s", peer->associd,
617 peer->assoc, peer->subject,
619 record_crypto_stats(&peer->srcadr, statstr);
622 printf("crypto_recv: %s\n", statstr);
627 * Decode X509 certificate in ASN.1 format and extract
628 * the data containing, among other things, subject
629 * name and public key. In the default identification
630 * scheme, the certificate trail is followed to a self
631 * signed trusted certificate.
633 case CRYPTO_CERT | CRYPTO_RESP:
636 * Discard the message if empty or invalid.
641 if ((rval = crypto_verify(ep, NULL, peer)) !=
646 * Scan the certificate list to delete old
647 * versions and link the newest version first on
648 * the list. Then, verify the signature. If the
649 * certificate is bad or missing, just ignore
652 if ((xinfo = cert_install(ep, peer)) == NULL) {
656 if ((rval = cert_hike(peer, xinfo)) != XEVNT_OK)
660 * We plug in the public key and lifetime from
661 * the first certificate received. However, note
662 * that this certificate might not be signed by
663 * the server, so we can't check the
664 * signature/digest NID.
666 if (peer->pkey == NULL) {
667 puch = xinfo->cert.ptr;
668 cert = d2i_X509(NULL, &puch,
669 ntohl(xinfo->cert.vallen));
670 peer->pkey = X509_get_pubkey(cert);
673 peer->flash &= ~TEST8;
675 snprintf(statstr, sizeof(statstr),
676 "cert %s %s 0x%x %s (%u) fs %u",
677 xinfo->subject, xinfo->issuer, xinfo->flags,
678 OBJ_nid2ln(temp32), temp32,
680 record_crypto_stats(&peer->srcadr, statstr);
683 printf("crypto_recv: %s\n", statstr);
688 * Schnorr (IFF) identity scheme. This scheme is
689 * designed for use with shared secret server group keys
690 * and where the certificate may be generated by a third
691 * party. The client sends a challenge to the server,
692 * which performs a calculation and returns the result.
693 * A positive result is possible only if both client and
694 * server contain the same secret group key.
696 case CRYPTO_IFF | CRYPTO_RESP:
699 * Discard the message if invalid.
701 if ((rval = crypto_verify(ep, NULL, peer)) !=
706 * If the challenge matches the response, the
707 * server public key, signature and identity are
708 * all verified at the same time. The server is
709 * declared trusted, so we skip further
710 * certificate exchanges and move immediately to
711 * the cookie exchange.
713 if ((rval = crypto_iff(ep, peer)) != XEVNT_OK)
716 peer->crypto |= CRYPTO_FLAG_VRFY;
717 peer->flash &= ~TEST8;
718 snprintf(statstr, sizeof(statstr), "iff %s fs %u",
719 peer->issuer, ntohl(ep->fstamp));
720 record_crypto_stats(&peer->srcadr, statstr);
723 printf("crypto_recv: %s\n", statstr);
728 * Guillou-Quisquater (GQ) identity scheme. This scheme
729 * is designed for use with public certificates carrying
730 * the GQ public key in an extension field. The client
731 * sends a challenge to the server, which performs a
732 * calculation and returns the result. A positive result
733 * is possible only if both client and server contain
734 * the same group key and the server has the matching GQ
737 case CRYPTO_GQ | CRYPTO_RESP:
740 * Discard the message if invalid
742 if ((rval = crypto_verify(ep, NULL, peer)) !=
747 * If the challenge matches the response, the
748 * server public key, signature and identity are
749 * all verified at the same time. The server is
750 * declared trusted, so we skip further
751 * certificate exchanges and move immediately to
752 * the cookie exchange.
754 if ((rval = crypto_gq(ep, peer)) != XEVNT_OK)
757 peer->crypto |= CRYPTO_FLAG_VRFY;
758 peer->flash &= ~TEST8;
759 snprintf(statstr, sizeof(statstr), "gq %s fs %u",
760 peer->issuer, ntohl(ep->fstamp));
761 record_crypto_stats(&peer->srcadr, statstr);
764 printf("crypto_recv: %s\n", statstr);
769 * Mu-Varadharajan (MV) identity scheme. This scheme is
770 * designed for use with three levels of trust, trusted
771 * host, server and client. The trusted host key is
772 * opaque to servers and clients; the server keys are
773 * opaque to clients and each client key is different.
774 * Client keys can be revoked without requiring new key
777 case CRYPTO_MV | CRYPTO_RESP:
780 * Discard the message if invalid.
782 if ((rval = crypto_verify(ep, NULL, peer)) !=
787 * If the challenge matches the response, the
788 * server public key, signature and identity are
789 * all verified at the same time. The server is
790 * declared trusted, so we skip further
791 * certificate exchanges and move immediately to
792 * the cookie exchange.
794 if ((rval = crypto_mv(ep, peer)) != XEVNT_OK)
797 peer->crypto |= CRYPTO_FLAG_VRFY;
798 peer->flash &= ~TEST8;
799 snprintf(statstr, sizeof(statstr), "mv %s fs %u",
800 peer->issuer, ntohl(ep->fstamp));
801 record_crypto_stats(&peer->srcadr, statstr);
804 printf("crypto_recv: %s\n", statstr);
810 * Cookie response in client and symmetric modes. If the
811 * cookie bit is set, the working cookie is the EXOR of
812 * the current and new values.
814 case CRYPTO_COOK | CRYPTO_RESP:
817 * Discard the message if invalid or signature
818 * not verified with respect to the cookie
821 if ((rval = crypto_verify(ep, &peer->cookval,
826 * Decrypt the cookie, hunting all the time for
829 if (vallen == (u_int)EVP_PKEY_size(host_pkey)) {
830 u_int32 *cookiebuf = malloc(
831 RSA_size(host_pkey->pkey.rsa));
837 if (RSA_private_decrypt(vallen,
841 RSA_PKCS1_OAEP_PADDING) != 4) {
846 cookie = ntohl(*cookiebuf);
855 * Install cookie values and light the cookie
856 * bit. If this is not broadcast client mode, we
860 if (hismode == MODE_ACTIVE || hismode ==
862 peer->pcookie = peer->hcookie ^ cookie;
864 peer->pcookie = cookie;
865 peer->crypto |= CRYPTO_FLAG_COOK;
866 peer->flash &= ~TEST8;
867 snprintf(statstr, sizeof(statstr),
868 "cook %x ts %u fs %u", peer->pcookie,
869 ntohl(ep->tstamp), ntohl(ep->fstamp));
870 record_crypto_stats(&peer->srcadr, statstr);
873 printf("crypto_recv: %s\n", statstr);
878 * Install autokey values in broadcast client and
879 * symmetric modes. We have to do this every time the
880 * sever/peer cookie changes or a new keylist is
881 * rolled. Ordinarily, this is automatic as this message
882 * is piggybacked on the first NTP packet sent upon
883 * either of these events. Note that a broadcast client
884 * or symmetric peer can receive this response without a
887 case CRYPTO_AUTO | CRYPTO_RESP:
890 * Discard the message if invalid or signature
891 * not verified with respect to the receive
894 if ((rval = crypto_verify(ep, &peer->recval,
899 * Discard the message if a broadcast client and
900 * the association ID does not match. This might
901 * happen if a broacast server restarts the
902 * protocol. A protocol restart will occur at
903 * the next ASSOC message.
905 if ((peer->cast_flags & MDF_BCLNT) &&
906 peer->assoc != associd)
910 * Install autokey values and light the
911 * autokey bit. This is not hard.
916 if (peer->recval.ptr == NULL)
918 emalloc(sizeof(struct autokey));
919 bp = (struct autokey *)peer->recval.ptr;
920 peer->recval.tstamp = ep->tstamp;
921 peer->recval.fstamp = ep->fstamp;
922 ap = (struct autokey *)ep->pkt;
923 bp->seq = ntohl(ap->seq);
924 bp->key = ntohl(ap->key);
925 peer->pkeyid = bp->key;
926 peer->crypto |= CRYPTO_FLAG_AUTO;
927 peer->flash &= ~TEST8;
928 snprintf(statstr, sizeof(statstr),
929 "auto seq %d key %x ts %u fs %u", bp->seq,
930 bp->key, ntohl(ep->tstamp),
932 record_crypto_stats(&peer->srcadr, statstr);
935 printf("crypto_recv: %s\n", statstr);
940 * X509 certificate sign response. Validate the
941 * certificate signed by the server and install. Later
942 * this can be provided to clients of this server in
943 * lieu of the self signed certificate in order to
944 * validate the public key.
946 case CRYPTO_SIGN | CRYPTO_RESP:
949 * Discard the message if invalid.
951 if ((rval = crypto_verify(ep, NULL, peer)) !=
956 * Scan the certificate list to delete old
957 * versions and link the newest version first on
960 if ((xinfo = cert_install(ep, peer)) == NULL) {
964 peer->crypto |= CRYPTO_FLAG_SIGN;
965 peer->flash &= ~TEST8;
967 snprintf(statstr, sizeof(statstr),
968 "sign %s %s 0x%x %s (%u) fs %u",
969 xinfo->subject, xinfo->issuer, xinfo->flags,
970 OBJ_nid2ln(temp32), temp32,
972 record_crypto_stats(&peer->srcadr, statstr);
975 printf("crypto_recv: %s\n", statstr);
980 * Install leapseconds values. While the leapsecond
981 * values epoch, TAI offset and values expiration epoch
982 * are retained, only the current TAI offset is provided
983 * via the kernel to other applications.
985 case CRYPTO_LEAP | CRYPTO_RESP:
987 * Discard the message if invalid. We can't
988 * compare the value timestamps here, as they
989 * can be updated by different servers.
991 if ((rval = crypto_verify(ep, NULL, peer)) !=
996 * If the packet leap values are more recent
997 * than the stored ones, install the new leap
998 * values and recompute the signatures.
1000 if (leapsec_add_fix(ntohl(ep->pkt[0]),
1005 leap_signature_t lsig;
1007 leapsec_getsig(&lsig);
1008 tai_leap.tstamp = ep->tstamp;
1009 tai_leap.fstamp = ep->fstamp;
1010 tai_leap.vallen = ep->vallen;
1012 mprintf_event(EVNT_TAI, peer,
1013 "%d leap %s expire %s", lsig.taiof,
1014 fstostr(lsig.ttime),
1015 fstostr(lsig.etime));
1017 peer->crypto |= CRYPTO_FLAG_LEAP;
1018 peer->flash &= ~TEST8;
1019 snprintf(statstr, sizeof(statstr),
1020 "leap TAI offset %d at %u expire %u fs %u",
1021 ntohl(ep->pkt[0]), ntohl(ep->pkt[1]),
1022 ntohl(ep->pkt[2]), ntohl(ep->fstamp));
1023 record_crypto_stats(&peer->srcadr, statstr);
1026 printf("crypto_recv: %s\n", statstr);
1031 * We come here in symmetric modes for miscellaneous
1032 * commands that have value fields but are processed on
1033 * the transmit side. All we need do here is check for
1034 * valid field length. Note that ASSOC is handled
1043 if (len < VALUE_LEN) {
1050 * We come here in symmetric modes for requests
1051 * requiring a response (above plus AUTO and LEAP) and
1052 * for responses. If a request, save the extension field
1053 * for later; invalid requests will be caught on the
1054 * transmit side. If an error or invalid response,
1055 * declare a protocol error.
1058 if (code & (CRYPTO_RESP | CRYPTO_ERROR)) {
1060 } else if (peer->cmmd == NULL) {
1062 memcpy(fp, ep, len);
1068 * The first error found terminates the extension field
1069 * scan and we return the laundry to the caller.
1071 if (rval != XEVNT_OK) {
1072 snprintf(statstr, sizeof(statstr),
1073 "%04x %d %02x %s", htonl(ep->opcode),
1074 associd, rval, eventstr(rval));
1075 record_crypto_stats(&peer->srcadr, statstr);
1078 printf("crypto_recv: %s\n", statstr);
1082 authlen += (len + 3) / 4 * 4;
1089 * crypto_xmit - construct extension fields
1091 * This routine is called both when an association is configured and
1092 * when one is not. The only case where this matters is to retrieve the
1093 * autokey information, in which case the caller has to provide the
1094 * association ID to match the association.
1096 * Side effect: update the packet offset.
1100 * XEVNT_CRT bad or missing certificate
1101 * XEVNT_ERR protocol error
1102 * XEVNT_LEN bad field format or length
1103 * XEVNT_PER host certificate expired
1107 struct peer *peer, /* peer structure pointer */
1108 struct pkt *xpkt, /* transmit packet pointer */
1109 struct recvbuf *rbufp, /* receive buffer pointer */
1110 int start, /* offset to extension field */
1111 struct exten *ep, /* extension pointer */
1112 keyid_t cookie /* session cookie */
1115 struct exten *fp; /* extension pointers */
1116 struct cert_info *cp, *xp, *yp; /* cert info/value pointer */
1117 sockaddr_u *srcadr_sin; /* source address */
1118 u_int32 *pkt; /* packet pointer */
1119 u_int opcode; /* extension field opcode */
1120 char certname[MAXHOSTNAME + 1]; /* subject name buffer */
1121 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1123 struct calendar tscal;
1132 * Generate the requested extension field request code, length
1133 * and association ID. If this is a response and the host is not
1134 * synchronized, light the error bit and go home.
1136 pkt = (u_int32 *)xpkt + start / 4;
1137 fp = (struct exten *)pkt;
1138 opcode = ntohl(ep->opcode);
1140 srcadr_sin = &peer->srcadr;
1141 if (!(opcode & CRYPTO_RESP))
1142 peer->opcode = ep->opcode;
1144 srcadr_sin = &rbufp->recv_srcadr;
1146 associd = (associd_t) ntohl(ep->associd);
1148 fp->opcode = htonl((opcode & 0xffff0000) | len);
1149 fp->associd = ep->associd;
1151 tstamp = crypto_time();
1152 switch (opcode & 0xffff0000) {
1155 * Send association request and response with status word and
1156 * host name. Note, this message is not signed and the filestamp
1157 * contains only the status word.
1160 case CRYPTO_ASSOC | CRYPTO_RESP:
1161 len = crypto_send(fp, &hostval, start);
1162 fp->fstamp = htonl(crypto_flags);
1166 * Send certificate request. Use the values from the extension
1170 memset(&vtemp, 0, sizeof(vtemp));
1171 vtemp.tstamp = ep->tstamp;
1172 vtemp.fstamp = ep->fstamp;
1173 vtemp.vallen = ep->vallen;
1174 vtemp.ptr = (u_char *)ep->pkt;
1175 len = crypto_send(fp, &vtemp, start);
1179 * Send sign request. Use the host certificate, which is self-
1180 * signed and may or may not be trusted.
1183 (void)ntpcal_ntp_to_date(&tscal, tstamp, NULL);
1184 if ((calcomp(&tscal, &(cert_host->first)) < 0)
1185 || (calcomp(&tscal, &(cert_host->last)) > 0))
1188 len = crypto_send(fp, &cert_host->cert, start);
1192 * Send certificate response. Use the name in the extension
1193 * field to find the certificate in the cache. If the request
1194 * contains no subject name, assume the name of this host. This
1195 * is for backwards compatibility. Private certificates are
1198 * There may be several certificates matching the request. First
1199 * choice is a self-signed trusted certificate; second choice is
1200 * any certificate signed by another host. There is no third
1203 case CRYPTO_CERT | CRYPTO_RESP:
1204 vallen = ntohl(ep->vallen); /* Must be <64k */
1205 if (vallen == 0 || vallen > MAXHOSTNAME ||
1206 len - VALUE_LEN < vallen) {
1212 * Find all public valid certificates with matching
1213 * subject. If a self-signed, trusted certificate is
1214 * found, use that certificate. If not, use the last non
1215 * self-signed certificate.
1217 memcpy(certname, ep->pkt, vallen);
1218 certname[vallen] = '\0';
1220 for (cp = cinfo; cp != NULL; cp = cp->link) {
1221 if (cp->flags & (CERT_PRIV | CERT_ERROR))
1224 if (strcmp(certname, cp->subject) != 0)
1227 if (strcmp(certname, cp->issuer) != 0)
1229 else if (cp ->flags & CERT_TRUST)
1235 * Be careful who you trust. If the certificate is not
1236 * found, return an empty response. Note that we dont
1237 * enforce lifetimes here.
1239 * The timestamp and filestamp are taken from the
1240 * certificate value structure. For all certificates the
1241 * timestamp is the latest signature update time. For
1242 * host and imported certificates the filestamp is the
1243 * creation epoch. For signed certificates the filestamp
1244 * is the creation epoch of the trusted certificate at
1245 * the root of the certificate trail. In principle, this
1246 * allows strong checking for signature masquerade.
1256 len = crypto_send(fp, &xp->cert, start);
1260 * Send challenge in Schnorr (IFF) identity scheme.
1264 break; /* hack attack */
1266 if ((rval = crypto_alice(peer, &vtemp)) == XEVNT_OK) {
1267 len = crypto_send(fp, &vtemp, start);
1273 * Send response in Schnorr (IFF) identity scheme.
1275 case CRYPTO_IFF | CRYPTO_RESP:
1276 if ((rval = crypto_bob(ep, &vtemp)) == XEVNT_OK) {
1277 len = crypto_send(fp, &vtemp, start);
1283 * Send challenge in Guillou-Quisquater (GQ) identity scheme.
1287 break; /* hack attack */
1289 if ((rval = crypto_alice2(peer, &vtemp)) == XEVNT_OK) {
1290 len = crypto_send(fp, &vtemp, start);
1296 * Send response in Guillou-Quisquater (GQ) identity scheme.
1298 case CRYPTO_GQ | CRYPTO_RESP:
1299 if ((rval = crypto_bob2(ep, &vtemp)) == XEVNT_OK) {
1300 len = crypto_send(fp, &vtemp, start);
1306 * Send challenge in MV identity scheme.
1310 break; /* hack attack */
1312 if ((rval = crypto_alice3(peer, &vtemp)) == XEVNT_OK) {
1313 len = crypto_send(fp, &vtemp, start);
1319 * Send response in MV identity scheme.
1321 case CRYPTO_MV | CRYPTO_RESP:
1322 if ((rval = crypto_bob3(ep, &vtemp)) == XEVNT_OK) {
1323 len = crypto_send(fp, &vtemp, start);
1329 * Send certificate sign response. The integrity of the request
1330 * certificate has already been verified on the receive side.
1331 * Sign the response using the local server key. Use the
1332 * filestamp from the request and use the timestamp as the
1333 * current time. Light the error bit if the certificate is
1334 * invalid or contains an unverified signature.
1336 case CRYPTO_SIGN | CRYPTO_RESP:
1337 if ((rval = cert_sign(ep, &vtemp)) == XEVNT_OK) {
1338 len = crypto_send(fp, &vtemp, start);
1344 * Send public key and signature. Use the values from the public
1348 len = crypto_send(fp, &pubkey, start);
1352 * Encrypt and send cookie and signature. Light the error bit if
1353 * anything goes wrong.
1355 case CRYPTO_COOK | CRYPTO_RESP:
1356 vallen = ntohl(ep->vallen); /* Must be <64k */
1358 || (vallen >= MAX_VALLEN)
1359 || (opcode & 0x0000ffff) < VALUE_LEN + vallen) {
1366 tcookie = peer->hcookie;
1367 if ((rval = crypto_encrypt((const u_char *)ep->pkt, vallen, &tcookie, &vtemp))
1369 len = crypto_send(fp, &vtemp, start);
1375 * Find peer and send autokey data and signature in broadcast
1376 * server and symmetric modes. Use the values in the autokey
1377 * structure. If no association is found, either the server has
1378 * restarted with new associations or some perp has replayed an
1379 * old message, in which case light the error bit.
1381 case CRYPTO_AUTO | CRYPTO_RESP:
1383 if ((peer = findpeerbyassoc(associd)) == NULL) {
1388 peer->flags &= ~FLAG_ASSOC;
1389 len = crypto_send(fp, &peer->sndval, start);
1393 * Send leapseconds values and signature. Use the values from
1394 * the tai structure. If no table has been loaded, just send an
1397 case CRYPTO_LEAP | CRYPTO_RESP:
1398 len = crypto_send(fp, &tai_leap, start);
1402 * Default - Send a valid command for unknown requests; send
1403 * an error response for unknown resonses.
1406 if (opcode & CRYPTO_RESP)
1411 * In case of error, flame the log. If a request, toss the
1412 * puppy; if a response, return so the sender can flame, too.
1414 if (rval != XEVNT_OK) {
1417 uint32 = CRYPTO_ERROR;
1419 fp->opcode |= htonl(uint32);
1420 snprintf(statstr, sizeof(statstr),
1421 "%04x %d %02x %s", opcode, associd, rval,
1423 record_crypto_stats(srcadr_sin, statstr);
1426 printf("crypto_xmit: %s\n", statstr);
1428 if (!(opcode & CRYPTO_RESP))
1434 "crypto_xmit: flags 0x%x offset %d len %d code 0x%x associd %d\n",
1435 crypto_flags, start, len, opcode >> 16, associd);
1442 * crypto_verify - verify the extension field value and signature
1446 * XEVNT_ERR protocol error
1447 * XEVNT_FSP bad filestamp
1448 * XEVNT_LEN bad field format or length
1449 * XEVNT_PUB bad or missing public key
1450 * XEVNT_SGL bad signature length
1451 * XEVNT_SIG signature not verified
1452 * XEVNT_TSP bad timestamp
1456 struct exten *ep, /* extension pointer */
1457 struct value *vp, /* value pointer */
1458 struct peer *peer /* peer structure pointer */
1461 EVP_PKEY *pkey; /* server public key */
1462 EVP_MD_CTX ctx; /* signature context */
1463 tstamp_t tstamp, tstamp1 = 0; /* timestamp */
1464 tstamp_t fstamp, fstamp1 = 0; /* filestamp */
1465 u_int vallen; /* value length */
1466 u_int siglen; /* signature length */
1471 * We are extremely parannoyed. We require valid opcode, length,
1472 * association ID, timestamp, filestamp, public key, digest,
1473 * signature length and signature, where relevant. Note that
1474 * preliminary length checks are done in the main loop.
1476 len = ntohl(ep->opcode) & 0x0000ffff;
1477 opcode = ntohl(ep->opcode) & 0xffff0000;
1480 * Check for valid value header, association ID and extension
1481 * field length. Remember, it is not an error to receive an
1482 * unsolicited response; however, the response ID must match
1483 * the association ID.
1485 if (opcode & CRYPTO_ERROR)
1488 if (len < VALUE_LEN)
1491 if (opcode == (CRYPTO_AUTO | CRYPTO_RESP) && (peer->pmode ==
1492 MODE_BROADCAST || (peer->cast_flags & MDF_BCLNT))) {
1493 if (ntohl(ep->associd) != peer->assoc)
1496 if (ntohl(ep->associd) != peer->associd)
1501 * We have a valid value header. Check for valid value and
1502 * signature field lengths. The extension field length must be
1503 * long enough to contain the value header, value and signature.
1504 * Note both the value and signature field lengths are rounded
1505 * up to the next word (4 octets).
1507 vallen = ntohl(ep->vallen);
1509 || vallen > MAX_VALLEN)
1512 i = (vallen + 3) / 4;
1513 siglen = ntohl(ep->pkt[i++]);
1514 if ( siglen > MAX_VALLEN
1515 || len - VALUE_LEN < ((vallen + 3) / 4) * 4
1516 || len - VALUE_LEN - ((vallen + 3) / 4) * 4
1517 < ((siglen + 3) / 4) * 4)
1521 * Check for valid timestamp and filestamp. If the timestamp is
1522 * zero, the sender is not synchronized and signatures are
1523 * not possible. If nonzero the timestamp must not precede the
1524 * filestamp. The timestamp and filestamp must not precede the
1525 * corresponding values in the value structure, if present.
1527 tstamp = ntohl(ep->tstamp);
1528 fstamp = ntohl(ep->fstamp);
1532 if (tstamp < fstamp)
1536 tstamp1 = ntohl(vp->tstamp);
1537 fstamp1 = ntohl(vp->fstamp);
1538 if (tstamp1 != 0 && fstamp1 != 0) {
1539 if (tstamp < tstamp1)
1542 if ((tstamp < fstamp1 || fstamp < fstamp1))
1548 * At the time the certificate message is validated, the public
1549 * key in the message is not available. Thus, don't try to
1550 * verify the signature.
1552 if (opcode == (CRYPTO_CERT | CRYPTO_RESP))
1556 * Check for valid signature length, public key and digest
1559 if (crypto_flags & peer->crypto & CRYPTO_FLAG_PRIV)
1563 if (siglen == 0 || pkey == NULL || peer->digest == NULL)
1566 if (siglen != (u_int)EVP_PKEY_size(pkey))
1570 * Darn, I thought we would never get here. Verify the
1571 * signature. If the identity exchange is verified, light the
1572 * proventic bit. What a relief.
1574 EVP_VerifyInit(&ctx, peer->digest);
1575 /* XXX: the "+ 12" needs to be at least documented... */
1576 EVP_VerifyUpdate(&ctx, (u_char *)&ep->tstamp, vallen + 12);
1577 if (EVP_VerifyFinal(&ctx, (u_char *)&ep->pkt[i], siglen,
1581 if (peer->crypto & CRYPTO_FLAG_VRFY)
1582 peer->crypto |= CRYPTO_FLAG_PROV;
1588 * crypto_encrypt - construct vp (encrypted cookie and signature) from
1589 * the public key and cookie.
1593 * XEVNT_CKY bad or missing cookie
1594 * XEVNT_PUB bad or missing public key
1598 const u_char *ptr, /* Public Key */
1599 u_int vallen, /* Length of Public Key */
1600 keyid_t *cookie, /* server cookie */
1601 struct value *vp /* value pointer */
1604 EVP_PKEY *pkey; /* public key */
1605 EVP_MD_CTX ctx; /* signature context */
1606 tstamp_t tstamp; /* NTP timestamp */
1611 * Extract the public key from the request.
1613 pkey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &ptr, vallen);
1615 msyslog(LOG_ERR, "crypto_encrypt: %s",
1616 ERR_error_string(ERR_get_error(), NULL));
1621 * Encrypt the cookie, encode in ASN.1 and sign.
1623 memset(vp, 0, sizeof(struct value));
1624 tstamp = crypto_time();
1625 vp->tstamp = htonl(tstamp);
1626 vp->fstamp = hostval.tstamp;
1627 vallen = EVP_PKEY_size(pkey);
1628 vp->vallen = htonl(vallen);
1629 vp->ptr = emalloc(vallen);
1631 temp32 = htonl(*cookie);
1632 if (RSA_public_encrypt(4, (u_char *)&temp32, puch,
1633 pkey->pkey.rsa, RSA_PKCS1_OAEP_PADDING) <= 0) {
1634 msyslog(LOG_ERR, "crypto_encrypt: %s",
1635 ERR_error_string(ERR_get_error(), NULL));
1637 EVP_PKEY_free(pkey);
1640 EVP_PKEY_free(pkey);
1644 vp->sig = emalloc(sign_siglen);
1645 EVP_SignInit(&ctx, sign_digest);
1646 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
1647 EVP_SignUpdate(&ctx, vp->ptr, vallen);
1648 if (EVP_SignFinal(&ctx, vp->sig, &vallen, sign_pkey))
1649 vp->siglen = htonl(sign_siglen);
1655 * crypto_ident - construct extension field for identity scheme
1657 * This routine determines which identity scheme is in use and
1658 * constructs an extension field for that scheme.
1661 * CRYTPO_IFF IFF scheme
1662 * CRYPTO_GQ GQ scheme
1663 * CRYPTO_MV MV scheme
1664 * CRYPTO_NULL no available scheme
1668 struct peer *peer /* peer structure pointer */
1671 char filename[MAXFILENAME];
1672 const char * scheme_name;
1676 * We come here after the group trusted host has been found; its
1677 * name defines the group name. Search the key cache for all
1678 * keys matching the same group name in order IFF, GQ and MV.
1679 * Use the first one available.
1682 if (peer->crypto & CRYPTO_FLAG_IFF) {
1683 scheme_name = "iff";
1684 scheme_id = CRYPTO_IFF;
1685 } else if (peer->crypto & CRYPTO_FLAG_GQ) {
1687 scheme_id = CRYPTO_GQ;
1688 } else if (peer->crypto & CRYPTO_FLAG_MV) {
1690 scheme_id = CRYPTO_MV;
1693 if (scheme_name != NULL) {
1694 snprintf(filename, sizeof(filename), "ntpkey_%spar_%s",
1695 scheme_name, peer->ident);
1696 peer->ident_pkey = crypto_key(filename, NULL,
1698 if (peer->ident_pkey != NULL)
1703 "crypto_ident: no identity parameters found for group %s",
1711 * crypto_args - construct extension field from arguments
1713 * This routine creates an extension field with current timestamps and
1714 * specified opcode, association ID and optional string. Note that the
1715 * extension field is created here, but freed after the crypto_xmit()
1716 * call in the protocol module.
1718 * Returns extension field pointer (no errors)
1720 * XXX: opcode and len should really be 32-bit quantities and
1721 * we should make sure that str is not too big.
1725 struct peer *peer, /* peer structure pointer */
1726 u_int opcode, /* operation code */
1727 associd_t associd, /* association ID */
1728 char *str /* argument string */
1731 tstamp_t tstamp; /* NTP timestamp */
1732 struct exten *ep; /* extension field pointer */
1733 u_int len; /* extension field length */
1736 tstamp = crypto_time();
1737 len = sizeof(struct exten);
1740 INSIST(slen < MAX_VALLEN);
1743 ep = emalloc_zero(len);
1747 REQUIRE(0 == (len & ~0x0000ffff));
1748 REQUIRE(0 == (opcode & ~0xffff0000));
1750 ep->opcode = htonl(opcode + len);
1751 ep->associd = htonl(associd);
1752 ep->tstamp = htonl(tstamp);
1753 ep->fstamp = hostval.tstamp;
1756 ep->vallen = htonl(slen);
1757 memcpy((char *)ep->pkt, str, slen);
1764 * crypto_send - construct extension field from value components
1766 * The value and signature fields are zero-padded to a word boundary.
1767 * Note: it is not polite to send a nonempty signature with zero
1768 * timestamp or a nonzero timestamp with an empty signature, but those
1769 * rules are not enforced here.
1771 * XXX This code won't work on a box with 16-bit ints.
1775 struct exten *ep, /* extension field pointer */
1776 struct value *vp, /* value pointer */
1777 int start /* buffer offset */
1780 u_int len, vallen, siglen, opcode;
1784 * Calculate extension field length and check for buffer
1785 * overflow. Leave room for the MAC.
1787 len = 16; /* XXX Document! */
1788 vallen = ntohl(vp->vallen);
1789 INSIST(vallen <= MAX_VALLEN);
1790 len += ((vallen + 3) / 4 + 1) * 4;
1791 siglen = ntohl(vp->siglen);
1792 len += ((siglen + 3) / 4 + 1) * 4;
1793 if (start + len > sizeof(struct pkt) - MAX_MAC_LEN)
1799 ep->tstamp = vp->tstamp;
1800 ep->fstamp = vp->fstamp;
1801 ep->vallen = vp->vallen;
1804 * Copy value. If the data field is empty or zero length,
1805 * encode an empty value with length zero.
1808 if (vallen > 0 && vp->ptr != NULL) {
1811 ep->pkt[i + j++] = 0;
1812 memcpy(&ep->pkt[i], vp->ptr, vallen);
1817 * Copy signature. If the signature field is empty or zero
1818 * length, encode an empty signature with length zero.
1820 ep->pkt[i++] = vp->siglen;
1821 if (siglen > 0 && vp->sig != NULL) {
1824 ep->pkt[i + j++] = 0;
1825 memcpy(&ep->pkt[i], vp->sig, siglen);
1828 opcode = ntohl(ep->opcode);
1829 ep->opcode = htonl((opcode & 0xffff0000) | len);
1830 ENSURE(len <= MAX_VALLEN);
1836 * crypto_update - compute new public value and sign extension fields
1838 * This routine runs periodically, like once a day, and when something
1839 * changes. It updates the timestamps on three value structures and one
1840 * value structure list, then signs all the structures:
1842 * hostval host name (not signed)
1844 * cinfo certificate info/value list
1845 * tai_leap leap values
1847 * Filestamps are proventic data, so this routine runs only when the
1848 * host is synchronized to a proventicated source. Thus, the timestamp
1849 * is proventic and can be used to deflect clogging attacks.
1851 * Returns void (no errors)
1856 EVP_MD_CTX ctx; /* message digest context */
1857 struct cert_info *cp; /* certificate info/value */
1858 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1861 leap_signature_t lsig;
1863 hostval.tstamp = htonl(crypto_time());
1864 if (hostval.tstamp == 0)
1868 * Sign public key and timestamps. The filestamp is derived from
1869 * the host key file extension from wherever the file was
1872 if (pubkey.vallen != 0) {
1873 pubkey.tstamp = hostval.tstamp;
1875 if (pubkey.sig == NULL)
1876 pubkey.sig = emalloc(sign_siglen);
1877 EVP_SignInit(&ctx, sign_digest);
1878 EVP_SignUpdate(&ctx, (u_char *)&pubkey, 12);
1879 EVP_SignUpdate(&ctx, pubkey.ptr, ntohl(pubkey.vallen));
1880 if (EVP_SignFinal(&ctx, pubkey.sig, &len, sign_pkey))
1881 pubkey.siglen = htonl(sign_siglen);
1885 * Sign certificates and timestamps. The filestamp is derived
1886 * from the certificate file extension from wherever the file
1887 * was generated. Note we do not throw expired certificates
1888 * away; they may have signed younger ones.
1890 for (cp = cinfo; cp != NULL; cp = cp->link) {
1891 cp->cert.tstamp = hostval.tstamp;
1892 cp->cert.siglen = 0;
1893 if (cp->cert.sig == NULL)
1894 cp->cert.sig = emalloc(sign_siglen);
1895 EVP_SignInit(&ctx, sign_digest);
1896 EVP_SignUpdate(&ctx, (u_char *)&cp->cert, 12);
1897 EVP_SignUpdate(&ctx, cp->cert.ptr,
1898 ntohl(cp->cert.vallen));
1899 if (EVP_SignFinal(&ctx, cp->cert.sig, &len, sign_pkey))
1900 cp->cert.siglen = htonl(sign_siglen);
1904 * Sign leapseconds values and timestamps. Note it is not an
1905 * error to return null values.
1907 tai_leap.tstamp = hostval.tstamp;
1908 tai_leap.fstamp = hostval.fstamp;
1909 len = 3 * sizeof(u_int32);
1910 if (tai_leap.ptr == NULL)
1911 tai_leap.ptr = emalloc(len);
1912 tai_leap.vallen = htonl(len);
1913 ptr = (u_int32 *)tai_leap.ptr;
1914 leapsec_getsig(&lsig);
1915 ptr[0] = htonl(lsig.taiof);
1916 ptr[1] = htonl(lsig.ttime);
1917 ptr[2] = htonl(lsig.etime);
1918 if (tai_leap.sig == NULL)
1919 tai_leap.sig = emalloc(sign_siglen);
1920 EVP_SignInit(&ctx, sign_digest);
1921 EVP_SignUpdate(&ctx, (u_char *)&tai_leap, 12);
1922 EVP_SignUpdate(&ctx, tai_leap.ptr, len);
1923 if (EVP_SignFinal(&ctx, tai_leap.sig, &len, sign_pkey))
1924 tai_leap.siglen = htonl(sign_siglen);
1926 crypto_flags |= CRYPTO_FLAG_TAI;
1927 snprintf(statstr, sizeof(statstr), "signature update ts %u",
1928 ntohl(hostval.tstamp));
1929 record_crypto_stats(NULL, statstr);
1932 printf("crypto_update: %s\n", statstr);
1938 * value_free - free value structure components.
1940 * Returns void (no errors)
1944 struct value *vp /* value structure */
1947 if (vp->ptr != NULL)
1949 if (vp->sig != NULL)
1951 memset(vp, 0, sizeof(struct value));
1956 * crypto_time - returns current NTP time.
1958 * Returns NTP seconds if in synch, 0 otherwise
1963 l_fp tstamp; /* NTP time */
1966 if (sys_leap != LEAP_NOTINSYNC)
1967 get_systime(&tstamp);
1968 return (tstamp.l_ui);
1973 * asn_to_calendar - convert ASN1_TIME time structure to struct calendar.
1979 ASN1_TIME *asn1time, /* pointer to ASN1_TIME structure */
1980 struct calendar *pjd /* pointer to result */
1983 size_t len; /* length of ASN1_TIME string */
1984 char v[24]; /* writable copy of ASN1_TIME string */
1985 unsigned long temp; /* result from strtoul */
1988 * Extract time string YYMMDDHHMMSSZ from ASN1 time structure.
1989 * Or YYYYMMDDHHMMSSZ.
1990 * Note that the YY, MM, DD fields start with one, the HH, MM,
1991 * SS fields start with zero and the Z character is ignored.
1992 * Also note that two-digit years less than 50 map to years greater than
1993 * 100. Dontcha love ASN.1? Better than MIL-188.
1995 len = asn1time->length;
1996 NTP_REQUIRE(len < sizeof(v));
1997 (void)strncpy(v, (char *)(asn1time->data), len);
1998 NTP_REQUIRE(len >= 13);
1999 temp = strtoul(v+len-3, NULL, 10);
2003 temp = strtoul(v+len-5, NULL, 10);
2007 temp = strtoul(v+len-7, NULL, 10);
2011 temp = strtoul(v+len-9, NULL, 10);
2012 pjd->monthday = temp;
2015 temp = strtoul(v+len-11, NULL, 10);
2019 temp = strtoul(v, NULL, 10);
2020 /* handle two-digit years */
2027 pjd->yearday = pjd->weekday = 0;
2033 * bigdig() - compute a BIGNUM MD5 hash of a BIGNUM number.
2035 * Returns void (no errors)
2039 BIGNUM *bn, /* BIGNUM * from */
2040 BIGNUM *bk /* BIGNUM * to */
2043 EVP_MD_CTX ctx; /* message digest context */
2044 u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
2045 u_char *ptr; /* a BIGNUM as binary string */
2048 len = BN_num_bytes(bn);
2051 EVP_DigestInit(&ctx, EVP_md5());
2052 EVP_DigestUpdate(&ctx, ptr, len);
2053 EVP_DigestFinal(&ctx, dgst, &len);
2054 BN_bin2bn(dgst, len, bk);
2060 ***********************************************************************
2062 * The following routines implement the Schnorr (IFF) identity scheme *
2064 ***********************************************************************
2066 * The Schnorr (IFF) identity scheme is intended for use when
2067 * certificates are generated by some other trusted certificate
2068 * authority and the certificate cannot be used to convey public
2069 * parameters. There are two kinds of files: encrypted server files that
2070 * contain private and public values and nonencrypted client files that
2071 * contain only public values. New generations of server files must be
2072 * securely transmitted to all servers of the group; client files can be
2073 * distributed by any means. The scheme is self contained and
2074 * independent of new generations of host keys, sign keys and
2077 * The IFF values hide in a DSA cuckoo structure which uses the same
2078 * parameters. The values are used by an identity scheme based on DSA
2079 * cryptography and described in Stimson p. 285. The p is a 512-bit
2080 * prime, g a generator of Zp* and q a 160-bit prime that divides p - 1
2081 * and is a qth root of 1 mod p; that is, g^q = 1 mod p. The TA rolls a
2082 * private random group key b (0 < b < q) and public key v = g^b, then
2083 * sends (p, q, g, b) to the servers and (p, q, g, v) to the clients.
2084 * Alice challenges Bob to confirm identity using the protocol described
2089 * The scheme goes like this. Both Alice and Bob have the public primes
2090 * p, q and generator g. The TA gives private key b to Bob and public
2093 * Alice rolls new random challenge r (o < r < q) and sends to Bob in
2094 * the IFF request message. Bob rolls new random k (0 < k < q), then
2095 * computes y = k + b r mod q and x = g^k mod p and sends (y, hash(x))
2096 * to Alice in the response message. Besides making the response
2097 * shorter, the hash makes it effectivey impossible for an intruder to
2098 * solve for b by observing a number of these messages.
2100 * Alice receives the response and computes g^y v^r mod p. After a bit
2101 * of algebra, this simplifies to g^k. If the hash of this result
2102 * matches hash(x), Alice knows that Bob has the group key b. The signed
2103 * response binds this knowledge to Bob's private key and the public key
2104 * previously received in his certificate.
2106 * crypto_alice - construct Alice's challenge in IFF scheme
2110 * XEVNT_ID bad or missing group key
2111 * XEVNT_PUB bad or missing public key
2115 struct peer *peer, /* peer pointer */
2116 struct value *vp /* value pointer */
2119 DSA *dsa; /* IFF parameters */
2120 BN_CTX *bctx; /* BIGNUM context */
2121 EVP_MD_CTX ctx; /* signature context */
2126 * The identity parameters must have correct format and content.
2128 if (peer->ident_pkey == NULL) {
2129 msyslog(LOG_NOTICE, "crypto_alice: scheme unavailable");
2133 if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) {
2134 msyslog(LOG_NOTICE, "crypto_alice: defective key");
2139 * Roll new random r (0 < r < q).
2141 if (peer->iffval != NULL)
2142 BN_free(peer->iffval);
2143 peer->iffval = BN_new();
2144 len = BN_num_bytes(dsa->q);
2145 BN_rand(peer->iffval, len * 8, -1, 1); /* r mod q*/
2146 bctx = BN_CTX_new();
2147 BN_mod(peer->iffval, peer->iffval, dsa->q, bctx);
2151 * Sign and send to Bob. The filestamp is from the local file.
2153 memset(vp, 0, sizeof(struct value));
2154 tstamp = crypto_time();
2155 vp->tstamp = htonl(tstamp);
2156 vp->fstamp = htonl(peer->ident_pkey->fstamp);
2157 vp->vallen = htonl(len);
2158 vp->ptr = emalloc(len);
2159 BN_bn2bin(peer->iffval, vp->ptr);
2163 vp->sig = emalloc(sign_siglen);
2164 EVP_SignInit(&ctx, sign_digest);
2165 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2166 EVP_SignUpdate(&ctx, vp->ptr, len);
2167 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2168 vp->siglen = htonl(sign_siglen);
2174 * crypto_bob - construct Bob's response to Alice's challenge
2178 * XEVNT_ERR protocol error
2179 * XEVNT_ID bad or missing group key
2183 struct exten *ep, /* extension pointer */
2184 struct value *vp /* value pointer */
2187 DSA *dsa; /* IFF parameters */
2188 DSA_SIG *sdsa; /* DSA signature context fake */
2189 BN_CTX *bctx; /* BIGNUM context */
2190 EVP_MD_CTX ctx; /* signature context */
2191 tstamp_t tstamp; /* NTP timestamp */
2192 BIGNUM *bn, *bk, *r;
2194 u_int len; /* extension field length */
2195 u_int vallen = 0; /* value length */
2198 * If the IFF parameters are not valid, something awful
2199 * happened or we are being tormented.
2201 if (iffkey_info == NULL) {
2202 msyslog(LOG_NOTICE, "crypto_bob: scheme unavailable");
2205 dsa = iffkey_info->pkey->pkey.dsa;
2208 * Extract r from the challenge.
2210 vallen = ntohl(ep->vallen);
2211 len = ntohl(ep->opcode) & 0x0000ffff;
2212 if (vallen == 0 || len < VALUE_LEN || len - VALUE_LEN < vallen)
2214 if ((r = BN_bin2bn((u_char *)ep->pkt, vallen, NULL)) == NULL) {
2215 msyslog(LOG_ERR, "crypto_bob: %s",
2216 ERR_error_string(ERR_get_error(), NULL));
2221 * Bob rolls random k (0 < k < q), computes y = k + b r mod q
2222 * and x = g^k mod p, then sends (y, hash(x)) to Alice.
2224 bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2225 sdsa = DSA_SIG_new();
2226 BN_rand(bk, vallen * 8, -1, 1); /* k */
2227 BN_mod_mul(bn, dsa->priv_key, r, dsa->q, bctx); /* b r mod q */
2229 BN_mod(bn, bn, dsa->q, bctx); /* k + b r mod q */
2230 sdsa->r = BN_dup(bn);
2231 BN_mod_exp(bk, dsa->g, bk, dsa->p, bctx); /* g^k mod p */
2233 sdsa->s = BN_dup(bk);
2235 BN_free(r); BN_free(bn); BN_free(bk);
2238 DSA_print_fp(stdout, dsa, 0);
2242 * Encode the values in ASN.1 and sign. The filestamp is from
2245 vallen = i2d_DSA_SIG(sdsa, NULL);
2247 msyslog(LOG_ERR, "crypto_bob: %s",
2248 ERR_error_string(ERR_get_error(), NULL));
2252 if (vallen > MAX_VALLEN) {
2253 msyslog(LOG_ERR, "crypto_bob: signature is too big: %d",
2258 memset(vp, 0, sizeof(struct value));
2259 tstamp = crypto_time();
2260 vp->tstamp = htonl(tstamp);
2261 vp->fstamp = htonl(iffkey_info->fstamp);
2262 vp->vallen = htonl(vallen);
2263 ptr = emalloc(vallen);
2265 i2d_DSA_SIG(sdsa, &ptr);
2270 /* XXX: more validation to make sure the sign fits... */
2271 vp->sig = emalloc(sign_siglen);
2272 EVP_SignInit(&ctx, sign_digest);
2273 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2274 EVP_SignUpdate(&ctx, vp->ptr, vallen);
2275 if (EVP_SignFinal(&ctx, vp->sig, &vallen, sign_pkey))
2276 vp->siglen = htonl(sign_siglen);
2282 * crypto_iff - verify Bob's response to Alice's challenge
2286 * XEVNT_FSP bad filestamp
2287 * XEVNT_ID bad or missing group key
2288 * XEVNT_PUB bad or missing public key
2292 struct exten *ep, /* extension pointer */
2293 struct peer *peer /* peer structure pointer */
2296 DSA *dsa; /* IFF parameters */
2297 BN_CTX *bctx; /* BIGNUM context */
2298 DSA_SIG *sdsa; /* DSA parameters */
2305 * If the IFF parameters are not valid or no challenge was sent,
2306 * something awful happened or we are being tormented.
2308 if (peer->ident_pkey == NULL) {
2309 msyslog(LOG_NOTICE, "crypto_iff: scheme unavailable");
2312 if (ntohl(ep->fstamp) != peer->ident_pkey->fstamp) {
2313 msyslog(LOG_NOTICE, "crypto_iff: invalid filestamp %u",
2317 if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) {
2318 msyslog(LOG_NOTICE, "crypto_iff: defective key");
2321 if (peer->iffval == NULL) {
2322 msyslog(LOG_NOTICE, "crypto_iff: missing challenge");
2327 * Extract the k + b r and g^k values from the response.
2329 bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2330 len = ntohl(ep->vallen);
2331 ptr = (u_char *)ep->pkt;
2332 if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2333 BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
2334 msyslog(LOG_ERR, "crypto_iff: %s",
2335 ERR_error_string(ERR_get_error(), NULL));
2340 * Compute g^(k + b r) g^(q - b)r mod p.
2342 BN_mod_exp(bn, dsa->pub_key, peer->iffval, dsa->p, bctx);
2343 BN_mod_exp(bk, dsa->g, sdsa->r, dsa->p, bctx);
2344 BN_mod_mul(bn, bn, bk, dsa->p, bctx);
2347 * Verify the hash of the result matches hash(x).
2350 temp = BN_cmp(bn, sdsa->s);
2351 BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
2352 BN_free(peer->iffval);
2353 peer->iffval = NULL;
2358 msyslog(LOG_NOTICE, "crypto_iff: identity not verified");
2364 ***********************************************************************
2366 * The following routines implement the Guillou-Quisquater (GQ) *
2369 ***********************************************************************
2371 * The Guillou-Quisquater (GQ) identity scheme is intended for use when
2372 * the certificate can be used to convey public parameters. The scheme
2373 * uses a X509v3 certificate extension field do convey the public key of
2374 * a private key known only to servers. There are two kinds of files:
2375 * encrypted server files that contain private and public values and
2376 * nonencrypted client files that contain only public values. New
2377 * generations of server files must be securely transmitted to all
2378 * servers of the group; client files can be distributed by any means.
2379 * The scheme is self contained and independent of new generations of
2380 * host keys and sign keys. The scheme is self contained and independent
2381 * of new generations of host keys and sign keys.
2383 * The GQ parameters hide in a RSA cuckoo structure which uses the same
2384 * parameters. The values are used by an identity scheme based on RSA
2385 * cryptography and described in Stimson p. 300 (with errors). The 512-
2386 * bit public modulus is n = p q, where p and q are secret large primes.
2387 * The TA rolls private random group key b as RSA exponent. These values
2388 * are known to all group members.
2390 * When rolling new certificates, a server recomputes the private and
2391 * public keys. The private key u is a random roll, while the public key
2392 * is the inverse obscured by the group key v = (u^-1)^b. These values
2393 * replace the private and public keys normally generated by the RSA
2394 * scheme. Alice challenges Bob to confirm identity using the protocol
2399 * The scheme goes like this. Both Alice and Bob have the same modulus n
2400 * and some random b as the group key. These values are computed and
2401 * distributed in advance via secret means, although only the group key
2402 * b is truly secret. Each has a private random private key u and public
2403 * key (u^-1)^b, although not necessarily the same ones. Bob and Alice
2404 * can regenerate the key pair from time to time without affecting
2405 * operations. The public key is conveyed on the certificate in an
2406 * extension field; the private key is never revealed.
2408 * Alice rolls new random challenge r and sends to Bob in the GQ
2409 * request message. Bob rolls new random k, then computes y = k u^r mod
2410 * n and x = k^b mod n and sends (y, hash(x)) to Alice in the response
2411 * message. Besides making the response shorter, the hash makes it
2412 * effectivey impossible for an intruder to solve for b by observing
2413 * a number of these messages.
2415 * Alice receives the response and computes y^b v^r mod n. After a bit
2416 * of algebra, this simplifies to k^b. If the hash of this result
2417 * matches hash(x), Alice knows that Bob has the group key b. The signed
2418 * response binds this knowledge to Bob's private key and the public key
2419 * previously received in his certificate.
2421 * crypto_alice2 - construct Alice's challenge in GQ scheme
2425 * XEVNT_ID bad or missing group key
2426 * XEVNT_PUB bad or missing public key
2430 struct peer *peer, /* peer pointer */
2431 struct value *vp /* value pointer */
2434 RSA *rsa; /* GQ parameters */
2435 BN_CTX *bctx; /* BIGNUM context */
2436 EVP_MD_CTX ctx; /* signature context */
2441 * The identity parameters must have correct format and content.
2443 if (peer->ident_pkey == NULL)
2446 if ((rsa = peer->ident_pkey->pkey->pkey.rsa) == NULL) {
2447 msyslog(LOG_NOTICE, "crypto_alice2: defective key");
2452 * Roll new random r (0 < r < n).
2454 if (peer->iffval != NULL)
2455 BN_free(peer->iffval);
2456 peer->iffval = BN_new();
2457 len = BN_num_bytes(rsa->n);
2458 BN_rand(peer->iffval, len * 8, -1, 1); /* r mod n */
2459 bctx = BN_CTX_new();
2460 BN_mod(peer->iffval, peer->iffval, rsa->n, bctx);
2464 * Sign and send to Bob. The filestamp is from the local file.
2466 memset(vp, 0, sizeof(struct value));
2467 tstamp = crypto_time();
2468 vp->tstamp = htonl(tstamp);
2469 vp->fstamp = htonl(peer->ident_pkey->fstamp);
2470 vp->vallen = htonl(len);
2471 vp->ptr = emalloc(len);
2472 BN_bn2bin(peer->iffval, vp->ptr);
2476 vp->sig = emalloc(sign_siglen);
2477 EVP_SignInit(&ctx, sign_digest);
2478 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2479 EVP_SignUpdate(&ctx, vp->ptr, len);
2480 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2481 vp->siglen = htonl(sign_siglen);
2487 * crypto_bob2 - construct Bob's response to Alice's challenge
2491 * XEVNT_ERR protocol error
2492 * XEVNT_ID bad or missing group key
2496 struct exten *ep, /* extension pointer */
2497 struct value *vp /* value pointer */
2500 RSA *rsa; /* GQ parameters */
2501 DSA_SIG *sdsa; /* DSA parameters */
2502 BN_CTX *bctx; /* BIGNUM context */
2503 EVP_MD_CTX ctx; /* signature context */
2504 tstamp_t tstamp; /* NTP timestamp */
2505 BIGNUM *r, *k, *g, *y;
2511 * If the GQ parameters are not valid, something awful
2512 * happened or we are being tormented.
2514 if (gqkey_info == NULL) {
2515 msyslog(LOG_NOTICE, "crypto_bob2: scheme unavailable");
2518 rsa = gqkey_info->pkey->pkey.rsa;
2521 * Extract r from the challenge.
2523 len = ntohl(ep->vallen);
2524 if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2525 msyslog(LOG_ERR, "crypto_bob2: %s",
2526 ERR_error_string(ERR_get_error(), NULL));
2531 * Bob rolls random k (0 < k < n), computes y = k u^r mod n and
2532 * x = k^b mod n, then sends (y, hash(x)) to Alice.
2534 bctx = BN_CTX_new(); k = BN_new(); g = BN_new(); y = BN_new();
2535 sdsa = DSA_SIG_new();
2536 BN_rand(k, len * 8, -1, 1); /* k */
2537 BN_mod(k, k, rsa->n, bctx);
2538 BN_mod_exp(y, rsa->p, r, rsa->n, bctx); /* u^r mod n */
2539 BN_mod_mul(y, k, y, rsa->n, bctx); /* k u^r mod n */
2540 sdsa->r = BN_dup(y);
2541 BN_mod_exp(g, k, rsa->e, rsa->n, bctx); /* k^b mod n */
2543 sdsa->s = BN_dup(g);
2545 BN_free(r); BN_free(k); BN_free(g); BN_free(y);
2548 RSA_print_fp(stdout, rsa, 0);
2552 * Encode the values in ASN.1 and sign. The filestamp is from
2555 len = s_len = i2d_DSA_SIG(sdsa, NULL);
2557 msyslog(LOG_ERR, "crypto_bob2: %s",
2558 ERR_error_string(ERR_get_error(), NULL));
2562 memset(vp, 0, sizeof(struct value));
2563 tstamp = crypto_time();
2564 vp->tstamp = htonl(tstamp);
2565 vp->fstamp = htonl(gqkey_info->fstamp);
2566 vp->vallen = htonl(len);
2569 i2d_DSA_SIG(sdsa, &ptr);
2574 vp->sig = emalloc(sign_siglen);
2575 EVP_SignInit(&ctx, sign_digest);
2576 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2577 EVP_SignUpdate(&ctx, vp->ptr, len);
2578 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2579 vp->siglen = htonl(sign_siglen);
2585 * crypto_gq - verify Bob's response to Alice's challenge
2589 * XEVNT_ERR protocol error
2590 * XEVNT_FSP bad filestamp
2591 * XEVNT_ID bad or missing group keys
2592 * XEVNT_PUB bad or missing public key
2596 struct exten *ep, /* extension pointer */
2597 struct peer *peer /* peer structure pointer */
2600 RSA *rsa; /* GQ parameters */
2601 BN_CTX *bctx; /* BIGNUM context */
2602 DSA_SIG *sdsa; /* RSA signature context fake */
2609 * If the GQ parameters are not valid or no challenge was sent,
2610 * something awful happened or we are being tormented. Note that
2611 * the filestamp on the local key file can be greater than on
2612 * the remote parameter file if the keys have been refreshed.
2614 if (peer->ident_pkey == NULL) {
2615 msyslog(LOG_NOTICE, "crypto_gq: scheme unavailable");
2618 if (ntohl(ep->fstamp) < peer->ident_pkey->fstamp) {
2619 msyslog(LOG_NOTICE, "crypto_gq: invalid filestamp %u",
2623 if ((rsa = peer->ident_pkey->pkey->pkey.rsa) == NULL) {
2624 msyslog(LOG_NOTICE, "crypto_gq: defective key");
2627 if (peer->iffval == NULL) {
2628 msyslog(LOG_NOTICE, "crypto_gq: missing challenge");
2633 * Extract the y = k u^r and hash(x = k^b) values from the
2636 bctx = BN_CTX_new(); y = BN_new(); v = BN_new();
2637 len = ntohl(ep->vallen);
2638 ptr = (u_char *)ep->pkt;
2639 if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2640 BN_CTX_free(bctx); BN_free(y); BN_free(v);
2641 msyslog(LOG_ERR, "crypto_gq: %s",
2642 ERR_error_string(ERR_get_error(), NULL));
2647 * Compute v^r y^b mod n.
2649 if (peer->grpkey == NULL) {
2650 msyslog(LOG_NOTICE, "crypto_gq: missing group key");
2653 BN_mod_exp(v, peer->grpkey, peer->iffval, rsa->n, bctx);
2655 BN_mod_exp(y, sdsa->r, rsa->e, rsa->n, bctx); /* y^b mod n */
2656 BN_mod_mul(y, v, y, rsa->n, bctx); /* v^r y^b mod n */
2659 * Verify the hash of the result matches hash(x).
2662 temp = BN_cmp(y, sdsa->s);
2663 BN_CTX_free(bctx); BN_free(y); BN_free(v);
2664 BN_free(peer->iffval);
2665 peer->iffval = NULL;
2670 msyslog(LOG_NOTICE, "crypto_gq: identity not verified");
2676 ***********************************************************************
2678 * The following routines implement the Mu-Varadharajan (MV) identity *
2681 ***********************************************************************
2683 * The Mu-Varadharajan (MV) cryptosystem was originally intended when
2684 * servers broadcast messages to clients, but clients never send
2685 * messages to servers. There is one encryption key for the server and a
2686 * separate decryption key for each client. It operated something like a
2687 * pay-per-view satellite broadcasting system where the session key is
2688 * encrypted by the broadcaster and the decryption keys are held in a
2689 * tamperproof set-top box.
2691 * The MV parameters and private encryption key hide in a DSA cuckoo
2692 * structure which uses the same parameters, but generated in a
2693 * different way. The values are used in an encryption scheme similar to
2694 * El Gamal cryptography and a polynomial formed from the expansion of
2695 * product terms (x - x[j]), as described in Mu, Y., and V.
2696 * Varadharajan: Robust and Secure Broadcasting, Proc. Indocrypt 2001,
2697 * 223-231. The paper has significant errors and serious omissions.
2699 * Let q be the product of n distinct primes s1[j] (j = 1...n), where
2700 * each s1[j] has m significant bits. Let p be a prime p = 2 * q + 1, so
2701 * that q and each s1[j] divide p - 1 and p has M = n * m + 1
2702 * significant bits. Let g be a generator of Zp; that is, gcd(g, p - 1)
2703 * = 1 and g^q = 1 mod p. We do modular arithmetic over Zq and then
2704 * project into Zp* as exponents of g. Sometimes we have to compute an
2705 * inverse b^-1 of random b in Zq, but for that purpose we require
2706 * gcd(b, q) = 1. We expect M to be in the 500-bit range and n
2707 * relatively small, like 30. These are the parameters of the scheme and
2708 * they are expensive to compute.
2710 * We set up an instance of the scheme as follows. A set of random
2711 * values x[j] mod q (j = 1...n), are generated as the zeros of a
2712 * polynomial of order n. The product terms (x - x[j]) are expanded to
2713 * form coefficients a[i] mod q (i = 0...n) in powers of x. These are
2714 * used as exponents of the generator g mod p to generate the private
2715 * encryption key A. The pair (gbar, ghat) of public server keys and the
2716 * pairs (xbar[j], xhat[j]) (j = 1...n) of private client keys are used
2717 * to construct the decryption keys. The devil is in the details.
2719 * This routine generates a private server encryption file including the
2720 * private encryption key E and partial decryption keys gbar and ghat.
2721 * It then generates public client decryption files including the public
2722 * keys xbar[j] and xhat[j] for each client j. The partial decryption
2723 * files are used to compute the inverse of E. These values are suitably
2724 * blinded so secrets are not revealed.
2726 * The distinguishing characteristic of this scheme is the capability to
2727 * revoke keys. Included in the calculation of E, gbar and ghat is the
2728 * product s = prod(s1[j]) (j = 1...n) above. If the factor s1[j] is
2729 * subsequently removed from the product and E, gbar and ghat
2730 * recomputed, the jth client will no longer be able to compute E^-1 and
2731 * thus unable to decrypt the messageblock.
2735 * The scheme goes like this. Bob has the server values (p, E, q, gbar,
2736 * ghat) and Alice has the client values (p, xbar, xhat).
2738 * Alice rolls new random nonce r mod p and sends to Bob in the MV
2739 * request message. Bob rolls random nonce k mod q, encrypts y = r E^k
2740 * mod p and sends (y, gbar^k, ghat^k) to Alice.
2742 * Alice receives the response and computes the inverse (E^k)^-1 from
2743 * the partial decryption keys gbar^k, ghat^k, xbar and xhat. She then
2744 * decrypts y and verifies it matches the original r. The signed
2745 * response binds this knowledge to Bob's private key and the public key
2746 * previously received in his certificate.
2748 * crypto_alice3 - construct Alice's challenge in MV scheme
2752 * XEVNT_ID bad or missing group key
2753 * XEVNT_PUB bad or missing public key
2757 struct peer *peer, /* peer pointer */
2758 struct value *vp /* value pointer */
2761 DSA *dsa; /* MV parameters */
2762 BN_CTX *bctx; /* BIGNUM context */
2763 EVP_MD_CTX ctx; /* signature context */
2768 * The identity parameters must have correct format and content.
2770 if (peer->ident_pkey == NULL)
2773 if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) {
2774 msyslog(LOG_NOTICE, "crypto_alice3: defective key");
2779 * Roll new random r (0 < r < q).
2781 if (peer->iffval != NULL)
2782 BN_free(peer->iffval);
2783 peer->iffval = BN_new();
2784 len = BN_num_bytes(dsa->p);
2785 BN_rand(peer->iffval, len * 8, -1, 1); /* r mod p */
2786 bctx = BN_CTX_new();
2787 BN_mod(peer->iffval, peer->iffval, dsa->p, bctx);
2791 * Sign and send to Bob. The filestamp is from the local file.
2793 memset(vp, 0, sizeof(struct value));
2794 tstamp = crypto_time();
2795 vp->tstamp = htonl(tstamp);
2796 vp->fstamp = htonl(peer->ident_pkey->fstamp);
2797 vp->vallen = htonl(len);
2798 vp->ptr = emalloc(len);
2799 BN_bn2bin(peer->iffval, vp->ptr);
2803 vp->sig = emalloc(sign_siglen);
2804 EVP_SignInit(&ctx, sign_digest);
2805 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2806 EVP_SignUpdate(&ctx, vp->ptr, len);
2807 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2808 vp->siglen = htonl(sign_siglen);
2814 * crypto_bob3 - construct Bob's response to Alice's challenge
2818 * XEVNT_ERR protocol error
2822 struct exten *ep, /* extension pointer */
2823 struct value *vp /* value pointer */
2826 DSA *dsa; /* MV parameters */
2827 DSA *sdsa; /* DSA signature context fake */
2828 BN_CTX *bctx; /* BIGNUM context */
2829 EVP_MD_CTX ctx; /* signature context */
2830 tstamp_t tstamp; /* NTP timestamp */
2836 * If the MV parameters are not valid, something awful
2837 * happened or we are being tormented.
2839 if (mvkey_info == NULL) {
2840 msyslog(LOG_NOTICE, "crypto_bob3: scheme unavailable");
2843 dsa = mvkey_info->pkey->pkey.dsa;
2846 * Extract r from the challenge.
2848 len = ntohl(ep->vallen);
2849 if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2850 msyslog(LOG_ERR, "crypto_bob3: %s",
2851 ERR_error_string(ERR_get_error(), NULL));
2856 * Bob rolls random k (0 < k < q), making sure it is not a
2857 * factor of q. He then computes y = r A^k and sends (y, gbar^k,
2858 * and ghat^k) to Alice.
2860 bctx = BN_CTX_new(); k = BN_new(); u = BN_new();
2862 sdsa->p = BN_new(); sdsa->q = BN_new(); sdsa->g = BN_new();
2864 BN_rand(k, BN_num_bits(dsa->q), 0, 0);
2865 BN_mod(k, k, dsa->q, bctx);
2866 BN_gcd(u, k, dsa->q, bctx);
2870 BN_mod_exp(u, dsa->g, k, dsa->p, bctx); /* A^k r */
2871 BN_mod_mul(sdsa->p, u, r, dsa->p, bctx);
2872 BN_mod_exp(sdsa->q, dsa->priv_key, k, dsa->p, bctx); /* gbar */
2873 BN_mod_exp(sdsa->g, dsa->pub_key, k, dsa->p, bctx); /* ghat */
2874 BN_CTX_free(bctx); BN_free(k); BN_free(r); BN_free(u);
2877 DSA_print_fp(stdout, sdsa, 0);
2881 * Encode the values in ASN.1 and sign. The filestamp is from
2884 memset(vp, 0, sizeof(struct value));
2885 tstamp = crypto_time();
2886 vp->tstamp = htonl(tstamp);
2887 vp->fstamp = htonl(mvkey_info->fstamp);
2888 len = i2d_DSAparams(sdsa, NULL);
2890 msyslog(LOG_ERR, "crypto_bob3: %s",
2891 ERR_error_string(ERR_get_error(), NULL));
2895 vp->vallen = htonl(len);
2898 i2d_DSAparams(sdsa, &ptr);
2903 vp->sig = emalloc(sign_siglen);
2904 EVP_SignInit(&ctx, sign_digest);
2905 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2906 EVP_SignUpdate(&ctx, vp->ptr, len);
2907 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2908 vp->siglen = htonl(sign_siglen);
2914 * crypto_mv - verify Bob's response to Alice's challenge
2918 * XEVNT_ERR protocol error
2919 * XEVNT_FSP bad filestamp
2920 * XEVNT_ID bad or missing group key
2921 * XEVNT_PUB bad or missing public key
2925 struct exten *ep, /* extension pointer */
2926 struct peer *peer /* peer structure pointer */
2929 DSA *dsa; /* MV parameters */
2930 DSA *sdsa; /* DSA parameters */
2931 BN_CTX *bctx; /* BIGNUM context */
2938 * If the MV parameters are not valid or no challenge was sent,
2939 * something awful happened or we are being tormented.
2941 if (peer->ident_pkey == NULL) {
2942 msyslog(LOG_NOTICE, "crypto_mv: scheme unavailable");
2945 if (ntohl(ep->fstamp) != peer->ident_pkey->fstamp) {
2946 msyslog(LOG_NOTICE, "crypto_mv: invalid filestamp %u",
2950 if ((dsa = peer->ident_pkey->pkey->pkey.dsa) == NULL) {
2951 msyslog(LOG_NOTICE, "crypto_mv: defective key");
2954 if (peer->iffval == NULL) {
2955 msyslog(LOG_NOTICE, "crypto_mv: missing challenge");
2960 * Extract the y, gbar and ghat values from the response.
2962 bctx = BN_CTX_new(); k = BN_new(); u = BN_new(); v = BN_new();
2963 len = ntohl(ep->vallen);
2964 ptr = (u_char *)ep->pkt;
2965 if ((sdsa = d2i_DSAparams(NULL, &ptr, len)) == NULL) {
2966 msyslog(LOG_ERR, "crypto_mv: %s",
2967 ERR_error_string(ERR_get_error(), NULL));
2972 * Compute (gbar^xhat ghat^xbar) mod p.
2974 BN_mod_exp(u, sdsa->q, dsa->pub_key, dsa->p, bctx);
2975 BN_mod_exp(v, sdsa->g, dsa->priv_key, dsa->p, bctx);
2976 BN_mod_mul(u, u, v, dsa->p, bctx);
2977 BN_mod_mul(u, u, sdsa->p, dsa->p, bctx);
2980 * The result should match r.
2982 temp = BN_cmp(u, peer->iffval);
2983 BN_CTX_free(bctx); BN_free(k); BN_free(u); BN_free(v);
2984 BN_free(peer->iffval);
2985 peer->iffval = NULL;
2990 msyslog(LOG_NOTICE, "crypto_mv: identity not verified");
2996 ***********************************************************************
2998 * The following routines are used to manipulate certificates *
3000 ***********************************************************************
3003 * cert_sign - sign x509 certificate equest and update value structure.
3005 * The certificate request includes a copy of the host certificate,
3006 * which includes the version number, subject name and public key of the
3007 * host. The resulting certificate includes these values plus the
3008 * serial number, issuer name and valid interval of the server. The
3009 * valid interval extends from the current time to the same time one
3010 * year hence. This may extend the life of the signed certificate beyond
3011 * that of the signer certificate.
3013 * It is convenient to use the NTP seconds of the current time as the
3014 * serial number. In the value structure the timestamp is the current
3015 * time and the filestamp is taken from the extension field. Note this
3016 * routine is called only when the client clock is synchronized to a
3017 * proventic source, so timestamp comparisons are valid.
3019 * The host certificate is valid from the time it was generated for a
3020 * period of one year. A signed certificate is valid from the time of
3021 * signature for a period of one year, but only the host certificate (or
3022 * sign certificate if used) is actually used to encrypt and decrypt
3023 * signatures. The signature trail is built from the client via the
3024 * intermediate servers to the trusted server. Each signature on the
3025 * trail must be valid at the time of signature, but it could happen
3026 * that a signer certificate expire before the signed certificate, which
3027 * remains valid until its expiration.
3031 * XEVNT_CRT bad or missing certificate
3032 * XEVNT_PER host certificate expired
3033 * XEVNT_PUB bad or missing public key
3034 * XEVNT_VFY certificate not verified
3038 struct exten *ep, /* extension field pointer */
3039 struct value *vp /* value pointer */
3042 X509 *req; /* X509 certificate request */
3043 X509 *cert; /* X509 certificate */
3044 X509_EXTENSION *ext; /* certificate extension */
3045 ASN1_INTEGER *serial; /* serial number */
3046 X509_NAME *subj; /* distinguished (common) name */
3047 EVP_PKEY *pkey; /* public key */
3048 EVP_MD_CTX ctx; /* message digest context */
3049 tstamp_t tstamp; /* NTP timestamp */
3050 struct calendar tscal;
3057 * Decode ASN.1 objects and construct certificate structure.
3058 * Make sure the system clock is synchronized to a proventic
3061 tstamp = crypto_time();
3065 cptr = (void *)ep->pkt;
3066 if ((req = d2i_X509(NULL, &cptr, ntohl(ep->vallen))) == NULL) {
3067 msyslog(LOG_ERR, "cert_sign: %s",
3068 ERR_error_string(ERR_get_error(), NULL));
3072 * Extract public key and check for errors.
3074 if ((pkey = X509_get_pubkey(req)) == NULL) {
3075 msyslog(LOG_ERR, "cert_sign: %s",
3076 ERR_error_string(ERR_get_error(), NULL));
3082 * Generate X509 certificate signed by this server. If this is a
3083 * trusted host, the issuer name is the group name; otherwise,
3084 * it is the host name. Also copy any extensions that might be
3088 X509_set_version(cert, X509_get_version(req));
3089 serial = ASN1_INTEGER_new();
3090 ASN1_INTEGER_set(serial, tstamp);
3091 X509_set_serialNumber(cert, serial);
3092 X509_gmtime_adj(X509_get_notBefore(cert), 0L);
3093 X509_gmtime_adj(X509_get_notAfter(cert), YEAR);
3094 subj = X509_get_issuer_name(cert);
3095 X509_NAME_add_entry_by_txt(subj, "commonName", MBSTRING_ASC,
3096 hostval.ptr, strlen((const char *)hostval.ptr), -1, 0);
3097 subj = X509_get_subject_name(req);
3098 X509_set_subject_name(cert, subj);
3099 X509_set_pubkey(cert, pkey);
3100 temp = X509_get_ext_count(req);
3101 for (i = 0; i < temp; i++) {
3102 ext = X509_get_ext(req, i);
3103 INSIST(X509_add_ext(cert, ext, -1));
3108 * Sign and verify the client certificate, but only if the host
3109 * certificate has not expired.
3111 (void)ntpcal_ntp_to_date(&tscal, tstamp, NULL);
3112 if ((calcomp(&tscal, &(cert_host->first)) < 0)
3113 || (calcomp(&tscal, &(cert_host->last)) > 0)) {
3117 X509_sign(cert, sign_pkey, sign_digest);
3118 if (X509_verify(cert, sign_pkey) <= 0) {
3119 msyslog(LOG_ERR, "cert_sign: %s",
3120 ERR_error_string(ERR_get_error(), NULL));
3124 len = i2d_X509(cert, NULL);
3127 * Build and sign the value structure. We have to sign it here,
3128 * since the response has to be returned right away. This is a
3131 memset(vp, 0, sizeof(struct value));
3132 vp->tstamp = htonl(tstamp);
3133 vp->fstamp = ep->fstamp;
3134 vp->vallen = htonl(len);
3135 vp->ptr = emalloc(len);
3137 i2d_X509(cert, (unsigned char **)(intptr_t)&ptr);
3140 vp->sig = emalloc(sign_siglen);
3141 EVP_SignInit(&ctx, sign_digest);
3142 EVP_SignUpdate(&ctx, (u_char *)vp, 12);
3143 EVP_SignUpdate(&ctx, vp->ptr, len);
3144 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
3145 vp->siglen = htonl(sign_siglen);
3149 X509_print_fp(stdout, cert);
3157 * cert_install - install certificate in certificate cache
3159 * This routine encodes an extension field into a certificate info/value
3160 * structure. It searches the certificate list for duplicates and
3161 * expunges whichever is older. Finally, it inserts this certificate
3162 * first on the list.
3164 * Returns certificate info pointer if valid, NULL if not.
3168 struct exten *ep, /* cert info/value */
3169 struct peer *peer /* peer structure */
3172 struct cert_info *cp, *xp, **zp;
3175 * Parse and validate the signed certificate. If valid,
3176 * construct the info/value structure; otherwise, scamper home
3179 if ((cp = cert_parse((u_char *)ep->pkt, (long)ntohl(ep->vallen),
3180 (tstamp_t)ntohl(ep->fstamp))) == NULL)
3184 * Scan certificate list looking for another certificate with
3185 * the same subject and issuer. If another is found with the
3186 * same or older filestamp, unlink it and return the goodies to
3187 * the heap. If another is found with a later filestamp, discard
3188 * the new one and leave the building with the old one.
3190 * Make a note to study this issue again. An earlier certificate
3191 * with a long lifetime might be overtaken by a later
3192 * certificate with a short lifetime, thus invalidating the
3193 * earlier signature. However, we gotta find a way to leak old
3194 * stuff from the cache, so we do it anyway.
3197 for (xp = cinfo; xp != NULL; xp = xp->link) {
3198 if (strcmp(cp->subject, xp->subject) == 0 &&
3199 strcmp(cp->issuer, xp->issuer) == 0) {
3200 if (ntohl(cp->cert.fstamp) <=
3201 ntohl(xp->cert.fstamp)) {
3217 cp->flags |= CERT_VALID;
3224 * cert_hike - verify the signature using the issuer public key
3228 * XEVNT_CRT bad or missing certificate
3229 * XEVNT_PER host certificate expired
3230 * XEVNT_VFY certificate not verified
3234 struct peer *peer, /* peer structure pointer */
3235 struct cert_info *yp /* issuer certificate */
3238 struct cert_info *xp; /* subject certificate */
3239 X509 *cert; /* X509 certificate */
3243 * Save the issuer on the new certificate, but remember the old
3246 if (peer->issuer != NULL)
3248 peer->issuer = estrdup(yp->issuer);
3253 * If subject Y matches issuer Y, then the certificate trail is
3254 * complete. If Y is not trusted, the server certificate has yet
3255 * been signed, so keep trying. Otherwise, save the group key
3256 * and light the valid bit. If the host certificate is trusted,
3257 * do not execute a sign exchange. If no identity scheme is in
3258 * use, light the identity and proventic bits.
3260 if (strcmp(yp->subject, yp->issuer) == 0) {
3261 if (!(yp->flags & CERT_TRUST))
3265 * If the server has an an identity scheme, fetch the
3266 * identity credentials. If not, the identity is
3267 * verified only by the trusted certificate. The next
3268 * signature will set the server proventic.
3270 peer->crypto |= CRYPTO_FLAG_CERT;
3271 peer->grpkey = yp->grpkey;
3272 if (peer->ident == NULL || !(peer->crypto &
3274 peer->crypto |= CRYPTO_FLAG_VRFY;
3278 * If X exists, verify signature X using public key Y.
3283 ptr = (u_char *)xp->cert.ptr;
3284 cert = d2i_X509(NULL, &ptr, ntohl(xp->cert.vallen));
3286 xp->flags |= CERT_ERROR;
3289 if (X509_verify(cert, yp->pkey) <= 0) {
3291 xp->flags |= CERT_ERROR;
3297 * Signature X is valid only if it begins during the
3300 if ((calcomp(&(xp->first), &(yp->first)) < 0)
3301 || (calcomp(&(xp->first), &(yp->last)) > 0)) {
3302 xp->flags |= CERT_ERROR;
3305 xp->flags |= CERT_SIGN;
3311 * cert_parse - parse x509 certificate and create info/value structures.
3313 * The server certificate includes the version number, issuer name,
3314 * subject name, public key and valid date interval. If the issuer name
3315 * is the same as the subject name, the certificate is self signed and
3316 * valid only if the server is configured as trustable. If the names are
3317 * different, another issuer has signed the server certificate and
3318 * vouched for it. In this case the server certificate is valid if
3319 * verified by the issuer public key.
3321 * Returns certificate info/value pointer if valid, NULL if not.
3323 struct cert_info * /* certificate information structure */
3325 const u_char *asn1cert, /* X509 certificate */
3326 long len, /* certificate length */
3327 tstamp_t fstamp /* filestamp */
3330 X509 *cert; /* X509 certificate */
3331 X509_EXTENSION *ext; /* X509v3 extension */
3332 struct cert_info *ret; /* certificate info/value */
3334 char pathbuf[MAXFILENAME];
3338 struct calendar fscal;
3341 * Decode ASN.1 objects and construct certificate structure.
3344 if ((cert = d2i_X509(NULL, &ptr, len)) == NULL) {
3345 msyslog(LOG_ERR, "cert_parse: %s",
3346 ERR_error_string(ERR_get_error(), NULL));
3351 X509_print_fp(stdout, cert);
3355 * Extract version, subject name and public key.
3357 ret = emalloc_zero(sizeof(*ret));
3358 if ((ret->pkey = X509_get_pubkey(cert)) == NULL) {
3359 msyslog(LOG_ERR, "cert_parse: %s",
3360 ERR_error_string(ERR_get_error(), NULL));
3365 ret->version = X509_get_version(cert);
3366 X509_NAME_oneline(X509_get_subject_name(cert), pathbuf,
3368 pch = strstr(pathbuf, "CN=");
3370 msyslog(LOG_NOTICE, "cert_parse: invalid subject %s",
3376 ret->subject = estrdup(pch + 3);
3379 * Extract remaining objects. Note that the NTP serial number is
3380 * the NTP seconds at the time of signing, but this might not be
3381 * the case for other authority. We don't bother to check the
3382 * objects at this time, since the real crunch can happen only
3383 * when the time is valid but not yet certificated.
3385 ret->nid = OBJ_obj2nid(cert->cert_info->signature->algorithm);
3386 ret->digest = (const EVP_MD *)EVP_get_digestbynid(ret->nid);
3388 (u_long)ASN1_INTEGER_get(X509_get_serialNumber(cert));
3389 X509_NAME_oneline(X509_get_issuer_name(cert), pathbuf,
3391 if ((pch = strstr(pathbuf, "CN=")) == NULL) {
3392 msyslog(LOG_NOTICE, "cert_parse: invalid issuer %s",
3398 ret->issuer = estrdup(pch + 3);
3399 asn_to_calendar(X509_get_notBefore(cert), &(ret->first));
3400 asn_to_calendar(X509_get_notAfter(cert), &(ret->last));
3403 * Extract extension fields. These are ad hoc ripoffs of
3404 * currently assigned functions and will certainly be changed
3405 * before prime time.
3407 cnt = X509_get_ext_count(cert);
3408 for (i = 0; i < cnt; i++) {
3409 ext = X509_get_ext(cert, i);
3410 temp = OBJ_obj2nid(ext->object);
3414 * If a key_usage field is present, we decode whether
3415 * this is a trusted or private certificate. This is
3416 * dorky; all we want is to compare NIDs, but OpenSSL
3417 * insists on BIO text strings.
3419 case NID_ext_key_usage:
3420 bp = BIO_new(BIO_s_mem());
3421 X509V3_EXT_print(bp, ext, 0, 0);
3422 BIO_gets(bp, pathbuf, sizeof(pathbuf));
3424 if (strcmp(pathbuf, "Trust Root") == 0)
3425 ret->flags |= CERT_TRUST;
3426 else if (strcmp(pathbuf, "Private") == 0)
3427 ret->flags |= CERT_PRIV;
3430 printf("cert_parse: %s: %s\n",
3431 OBJ_nid2ln(temp), pathbuf);
3436 * If a NID_subject_key_identifier field is present, it
3437 * contains the GQ public key.
3439 case NID_subject_key_identifier:
3440 ret->grpkey = BN_bin2bn(&ext->value->data[2],
3441 ext->value->length - 2, NULL);
3446 printf("cert_parse: %s\n",
3451 if (strcmp(ret->subject, ret->issuer) == 0) {
3454 * If certificate is self signed, verify signature.
3456 if (X509_verify(cert, ret->pkey) <= 0) {
3458 "cert_parse: signature not verified %s",
3467 * Check for a certificate loop.
3469 if (strcmp((const char *)hostval.ptr, ret->issuer) == 0) {
3471 "cert_parse: certificate trail loop %s",
3480 * Verify certificate valid times. Note that certificates cannot
3483 (void)ntpcal_ntp_to_date(&fscal, fstamp, NULL);
3484 if ((calcomp(&(ret->first), &(ret->last)) > 0)
3485 || (calcomp(&(ret->first), &fscal) < 0)) {
3487 "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",
3489 ret->first.year, ret->first.month, ret->first.monthday,
3490 ret->first.hour, ret->first.minute, ret->first.second,
3491 ret->last.year, ret->last.month, ret->last.monthday,
3492 ret->last.hour, ret->last.minute, ret->last.second,
3493 fscal.year, fscal.month, fscal.monthday,
3494 fscal.hour, fscal.minute, fscal.second);
3501 * Build the value structure to sign and send later.
3503 ret->cert.fstamp = htonl(fstamp);
3504 ret->cert.vallen = htonl(len);
3505 ret->cert.ptr = emalloc(len);
3506 memcpy(ret->cert.ptr, asn1cert, len);
3513 * cert_free - free certificate information structure
3517 struct cert_info *cinf /* certificate info/value structure */
3520 if (cinf->pkey != NULL)
3521 EVP_PKEY_free(cinf->pkey);
3522 if (cinf->subject != NULL)
3523 free(cinf->subject);
3524 if (cinf->issuer != NULL)
3526 if (cinf->grpkey != NULL)
3527 BN_free(cinf->grpkey);
3528 value_free(&cinf->cert);
3534 * crypto_key - load cryptographic parameters and keys
3536 * This routine searches the key cache for matching name in the form
3537 * ntpkey_<key>_<name>, where <key> is one of host, sign, iff, gq, mv,
3538 * and <name> is the host/group name. If not found, it tries to load a
3539 * PEM-encoded file of the same name and extracts the filestamp from
3540 * the first line of the file name. It returns the key pointer if valid,
3543 static struct pkey_info *
3545 char *cp, /* file name */
3546 char *passwd1, /* password */
3547 sockaddr_u *addr /* IP address */
3550 FILE *str; /* file handle */
3551 struct pkey_info *pkp; /* generic key */
3552 EVP_PKEY *pkey = NULL; /* public/private key */
3554 char filename[MAXFILENAME]; /* name of key file */
3555 char linkname[MAXFILENAME]; /* filestamp buffer) */
3556 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3560 * Search the key cache for matching key and name.
3562 for (pkp = pkinfo; pkp != NULL; pkp = pkp->link) {
3563 if (strcmp(cp, pkp->name) == 0)
3568 * Open the key file. If the first character of the file name is
3569 * not '/', prepend the keys directory string. If something goes
3570 * wrong, abandon ship.
3573 strlcpy(filename, cp, sizeof(filename));
3575 snprintf(filename, sizeof(filename), "%s/%s", keysdir,
3577 str = fopen(filename, "r");
3582 * Read the filestamp, which is contained in the first line.
3584 if ((ptr = fgets(linkname, sizeof(linkname), str)) == NULL) {
3585 msyslog(LOG_ERR, "crypto_key: empty file %s",
3590 if ((ptr = strrchr(ptr, '.')) == NULL) {
3591 msyslog(LOG_ERR, "crypto_key: no filestamp %s",
3596 if (sscanf(++ptr, "%u", &fstamp) != 1) {
3597 msyslog(LOG_ERR, "crypto_key: invalid filestamp %s",
3604 * Read and decrypt PEM-encoded private key. If it fails to
3605 * decrypt, game over.
3607 pkey = PEM_read_PrivateKey(str, NULL, NULL, passwd1);
3610 msyslog(LOG_ERR, "crypto_key: %s",
3611 ERR_error_string(ERR_get_error(), NULL));
3616 * Make a new entry in the key cache.
3618 pkp = emalloc(sizeof(struct pkey_info));
3622 pkp->name = estrdup(cp);
3623 pkp->fstamp = fstamp;
3626 * Leave tracks in the cryptostats.
3628 if ((ptr = strrchr(linkname, '\n')) != NULL)
3630 snprintf(statstr, sizeof(statstr), "%s mod %d", &linkname[2],
3631 EVP_PKEY_size(pkey) * 8);
3632 record_crypto_stats(addr, statstr);
3635 printf("crypto_key: %s\n", statstr);
3637 if (pkey->type == EVP_PKEY_DSA)
3638 DSA_print_fp(stdout, pkey->pkey.dsa, 0);
3639 else if (pkey->type == EVP_PKEY_RSA)
3640 RSA_print_fp(stdout, pkey->pkey.rsa, 0);
3648 ***********************************************************************
3650 * The following routines are used only at initialization time *
3652 ***********************************************************************
3655 * crypto_cert - load certificate from file
3657 * This routine loads an X.509 RSA or DSA certificate from a file and
3658 * constructs a info/cert value structure for this machine. The
3659 * structure includes a filestamp extracted from the file name. Later
3660 * the certificate can be sent to another machine on request.
3662 * Returns certificate info/value pointer if valid, NULL if not.
3664 static struct cert_info * /* certificate information */
3666 char *cp /* file name */
3669 struct cert_info *ret; /* certificate information */
3670 FILE *str; /* file handle */
3671 char filename[MAXFILENAME]; /* name of certificate file */
3672 char linkname[MAXFILENAME]; /* filestamp buffer */
3673 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3674 tstamp_t fstamp; /* filestamp */
3677 char *name, *header;
3681 * Open the certificate file. If the first character of the file
3682 * name is not '/', prepend the keys directory string. If
3683 * something goes wrong, abandon ship.
3686 strlcpy(filename, cp, sizeof(filename));
3688 snprintf(filename, sizeof(filename), "%s/%s", keysdir,
3690 str = fopen(filename, "r");
3695 * Read the filestamp, which is contained in the first line.
3697 if ((ptr = fgets(linkname, sizeof(linkname), str)) == NULL) {
3698 msyslog(LOG_ERR, "crypto_cert: empty file %s",
3703 if ((ptr = strrchr(ptr, '.')) == NULL) {
3704 msyslog(LOG_ERR, "crypto_cert: no filestamp %s",
3709 if (sscanf(++ptr, "%u", &fstamp) != 1) {
3710 msyslog(LOG_ERR, "crypto_cert: invalid filestamp %s",
3717 * Read PEM-encoded certificate and install.
3719 if (!PEM_read(str, &name, &header, &data, &len)) {
3720 msyslog(LOG_ERR, "crypto_cert: %s",
3721 ERR_error_string(ERR_get_error(), NULL));
3727 if (strcmp(name, "CERTIFICATE") != 0) {
3728 msyslog(LOG_NOTICE, "crypto_cert: wrong PEM type %s",
3737 * Parse certificate and generate info/value structure. The
3738 * pointer and copy nonsense is due something broken in Solaris.
3740 ret = cert_parse(data, len, fstamp);
3745 if ((ptr = strrchr(linkname, '\n')) != NULL)
3747 snprintf(statstr, sizeof(statstr), "%s 0x%x len %lu",
3748 &linkname[2], ret->flags, len);
3749 record_crypto_stats(NULL, statstr);
3752 printf("crypto_cert: %s\n", statstr);
3759 * crypto_setup - load keys, certificate and identity parameters
3761 * This routine loads the public/private host key and certificate. If
3762 * available, it loads the public/private sign key, which defaults to
3763 * the host key. The host key must be RSA, but the sign key can be
3764 * either RSA or DSA. If a trusted certificate, it loads the identity
3765 * parameters. In either case, the public key on the certificate must
3766 * agree with the sign key.
3768 * Required but missing files and inconsistent data and errors are
3769 * fatal. Allowing configuration to continue would be hazardous and
3770 * require really messy error checks.
3775 struct pkey_info *pinfo; /* private/public key */
3776 char filename[MAXFILENAME]; /* file name buffer */
3777 char hostname[MAXFILENAME]; /* host name buffer */
3779 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3780 l_fp seed; /* crypto PRNG seed as NTP timestamp */
3786 * Check for correct OpenSSL version and avoid initialization in
3787 * the case of multiple crypto commands.
3789 if (crypto_flags & CRYPTO_FLAG_ENAB) {
3791 "crypto_setup: spurious crypto command");
3794 ssl_check_version();
3797 * Load required random seed file and seed the random number
3798 * generator. Be default, it is found as .rnd in the user home
3799 * directory. The root home directory may be / or /root,
3800 * depending on the system. Wiggle the contents a bit and write
3801 * it back so the sequence does not repeat when we next restart.
3803 if (!RAND_status()) {
3804 if (rand_file == NULL) {
3805 RAND_file_name(filename, sizeof(filename));
3806 randfile = filename;
3807 } else if (*rand_file != '/') {
3808 snprintf(filename, sizeof(filename), "%s/%s",
3809 keysdir, rand_file);
3810 randfile = filename;
3812 randfile = rand_file;
3814 if ((bytes = RAND_load_file(randfile, -1)) == 0) {
3816 "crypto_setup: random seed file %s missing",
3820 arc4random_buf(&seed, sizeof(l_fp));
3821 RAND_seed(&seed, sizeof(l_fp));
3822 RAND_write_file(randfile);
3826 "crypto_setup: OpenSSL version %lx random seed file %s bytes read %d\n",
3827 SSLeay(), randfile, bytes);
3832 * Initialize structures.
3834 gethostname(hostname, sizeof(hostname));
3835 if (host_filename != NULL)
3836 strlcpy(hostname, host_filename, sizeof(hostname));
3838 passwd = estrdup(hostname);
3839 memset(&hostval, 0, sizeof(hostval));
3840 memset(&pubkey, 0, sizeof(pubkey));
3841 memset(&tai_leap, 0, sizeof(tai_leap));
3844 * Load required host key from file "ntpkey_host_<hostname>". If
3845 * no host key file is not found or has invalid password, life
3846 * as we know it ends. The host key also becomes the default
3849 snprintf(filename, sizeof(filename), "ntpkey_host_%s", hostname);
3850 pinfo = crypto_key(filename, passwd, NULL);
3851 if (pinfo == NULL) {
3853 "crypto_setup: host key file %s not found or corrupt",
3857 if (pinfo->pkey->type != EVP_PKEY_RSA) {
3859 "crypto_setup: host key is not RSA key type");
3862 host_pkey = pinfo->pkey;
3863 sign_pkey = host_pkey;
3864 hostval.fstamp = htonl(pinfo->fstamp);
3867 * Construct public key extension field for agreement scheme.
3869 len = i2d_PublicKey(host_pkey, NULL);
3872 i2d_PublicKey(host_pkey, &ptr);
3873 pubkey.fstamp = hostval.fstamp;
3874 pubkey.vallen = htonl(len);
3877 * Load optional sign key from file "ntpkey_sign_<hostname>". If
3878 * available, it becomes the sign key.
3880 snprintf(filename, sizeof(filename), "ntpkey_sign_%s", hostname);
3881 pinfo = crypto_key(filename, passwd, NULL);
3883 sign_pkey = pinfo->pkey;
3886 * Load required certificate from file "ntpkey_cert_<hostname>".
3888 snprintf(filename, sizeof(filename), "ntpkey_cert_%s", hostname);
3889 cinfo = crypto_cert(filename);
3890 if (cinfo == NULL) {
3892 "crypto_setup: certificate file %s not found or corrupt",
3897 sign_digest = cinfo->digest;
3898 sign_siglen = EVP_PKEY_size(sign_pkey);
3899 if (cinfo->flags & CERT_PRIV)
3900 crypto_flags |= CRYPTO_FLAG_PRIV;
3903 * The certificate must be self-signed.
3905 if (strcmp(cinfo->subject, cinfo->issuer) != 0) {
3907 "crypto_setup: certificate %s is not self-signed",
3911 hostval.ptr = estrdup(cinfo->subject);
3912 hostval.vallen = htonl(strlen(cinfo->subject));
3913 sys_hostname = hostval.ptr;
3914 ptr = (u_char *)strchr(sys_hostname, '@');
3916 sys_groupname = estrdup((char *)++ptr);
3917 if (ident_filename != NULL)
3918 strlcpy(hostname, ident_filename, sizeof(hostname));
3921 * Load optional IFF parameters from file
3922 * "ntpkey_iffkey_<hostname>".
3924 snprintf(filename, sizeof(filename), "ntpkey_iffkey_%s",
3926 iffkey_info = crypto_key(filename, passwd, NULL);
3927 if (iffkey_info != NULL)
3928 crypto_flags |= CRYPTO_FLAG_IFF;
3931 * Load optional GQ parameters from file
3932 * "ntpkey_gqkey_<hostname>".
3934 snprintf(filename, sizeof(filename), "ntpkey_gqkey_%s",
3936 gqkey_info = crypto_key(filename, passwd, NULL);
3937 if (gqkey_info != NULL)
3938 crypto_flags |= CRYPTO_FLAG_GQ;
3941 * Load optional MV parameters from file
3942 * "ntpkey_mvkey_<hostname>".
3944 snprintf(filename, sizeof(filename), "ntpkey_mvkey_%s",
3946 mvkey_info = crypto_key(filename, passwd, NULL);
3947 if (mvkey_info != NULL)
3948 crypto_flags |= CRYPTO_FLAG_MV;
3951 * We met the enemy and he is us. Now strike up the dance.
3953 crypto_flags |= CRYPTO_FLAG_ENAB | (cinfo->nid << 16);
3954 snprintf(statstr, sizeof(statstr), "setup 0x%x host %s %s",
3955 crypto_flags, hostname, OBJ_nid2ln(cinfo->nid));
3956 record_crypto_stats(NULL, statstr);
3959 printf("crypto_setup: %s\n", statstr);
3965 * crypto_config - configure data from the crypto command.
3969 int item, /* configuration item */
3970 char *cp /* item name */
3977 printf("crypto_config: item %d %s\n", item, cp);
3982 * Set host name (host).
3984 case CRYPTO_CONF_PRIV:
3985 if (NULL != host_filename)
3986 free(host_filename);
3987 host_filename = estrdup(cp);
3991 * Set group name (ident).
3993 case CRYPTO_CONF_IDENT:
3994 if (NULL != ident_filename)
3995 free(ident_filename);
3996 ident_filename = estrdup(cp);
4000 * Set private key password (pw).
4002 case CRYPTO_CONF_PW:
4005 passwd = estrdup(cp);
4009 * Set random seed file name (randfile).
4011 case CRYPTO_CONF_RAND:
4012 if (NULL != rand_file)
4014 rand_file = estrdup(cp);
4018 * Set message digest NID.
4020 case CRYPTO_CONF_NID:
4021 nid = OBJ_sn2nid(cp);
4024 "crypto_config: invalid digest name %s", cp);
4030 # else /* !AUTOKEY follows */
4031 int ntp_crypto_bs_pubkey;
4032 # endif /* !AUTOKEY */