2 * ntp_crypto.c - NTP version 4 public key routines
10 #include <sys/types.h>
11 #include <sys/param.h>
16 #include "ntp_stdlib.h"
17 #include "ntp_unixtime.h"
18 #include "ntp_string.h"
20 #include "openssl/asn1_mac.h"
21 #include "openssl/bn.h"
22 #include "openssl/err.h"
23 #include "openssl/evp.h"
24 #include "openssl/pem.h"
25 #include "openssl/rand.h"
26 #include "openssl/x509v3.h"
29 #include "ntp_syscall.h"
30 #endif /* KERNEL_PLL */
33 * Extension field message format
35 * These are always signed and saved before sending in network byte
36 * order. They must be converted to and from host byte order for
40 * | op | len | <- extension pointer
44 * | timestamp | <- value pointer
61 * The CRYPTO_RESP bit is set to 0 for requests, 1 for responses.
62 * Requests carry the association ID of the receiver; responses carry
63 * the association ID of the sender. Some messages include only the
64 * operation/length and association ID words and so have length 8
65 * octets. Ohers include the value structure and associated value and
66 * signature fields. These messages include the timestamp, filestamp,
67 * value and signature words and so have length at least 24 octets. The
68 * signature and/or value fields can be empty, in which case the
69 * respective length words are zero. An empty value with nonempty
70 * signature is syntactically valid, but semantically questionable.
72 * The filestamp represents the time when a cryptographic data file such
73 * as a public/private key pair is created. It follows every reference
74 * depending on that file and serves as a means to obsolete earlier data
75 * of the same type. The timestamp represents the time when the
76 * cryptographic data of the message were last signed. Creation of a
77 * cryptographic data file or signing a message can occur only when the
78 * creator or signor is synchronized to an authoritative source and
79 * proventicated to a trusted authority.
81 * Note there are four conditions required for server trust. First, the
82 * public key on the certificate must be verified, which involves a
83 * number of format, content and consistency checks. Next, the server
84 * identity must be confirmed by one of four schemes: private
85 * certificate, IFF scheme, GQ scheme or certificate trail hike to a
86 * self signed trusted certificate. Finally, the server signature must
92 #define TAI_1972 10 /* initial TAI offset (s) */
93 #define MAX_LEAP 100 /* max UTC leapseconds (s) */
94 #define VALUE_LEN (6 * 4) /* min response field length */
95 #define YEAR (60 * 60 * 24 * 365) /* seconds in year */
98 * Global cryptodata in host byte order
100 u_int32 crypto_flags = 0x0; /* status word */
101 u_int sys_tai; /* current UTC offset from TAI */
104 * Global cryptodata in network byte order
106 struct cert_info *cinfo = NULL; /* certificate info/value */
107 struct value hostval; /* host value */
108 struct value pubkey; /* public key */
109 struct value tai_leap; /* leapseconds table */
112 * Private cryptodata in host byte order
114 static char *passwd = NULL; /* private key password */
115 static EVP_PKEY *host_pkey = NULL; /* host key */
116 static EVP_PKEY *sign_pkey = NULL; /* sign key */
117 static EVP_PKEY *iffpar_pkey = NULL; /* IFF parameters */
118 static EVP_PKEY *gqpar_pkey = NULL; /* GQ parameters */
119 static EVP_PKEY *mvpar_pkey = NULL; /* MV parameters */
120 static const EVP_MD *sign_digest = NULL; /* sign digest */
121 static u_int sign_siglen; /* sign key length */
122 static char *rand_file = NULL; /* random seed file */
123 static char *host_file = NULL; /* host key file */
124 static char *sign_file = NULL; /* sign key file */
125 static char *iffpar_file = NULL; /* IFF parameters file */
126 static char *gqpar_file = NULL; /* GQ parameters file */
127 static char *mvpar_file = NULL; /* MV parameters file */
128 static char *cert_file = NULL; /* certificate file */
129 static char *leap_file = NULL; /* leapseconds file */
130 static tstamp_t if_fstamp = 0; /* IFF file stamp */
131 static tstamp_t gq_fstamp = 0; /* GQ file stamp */
132 static tstamp_t mv_fstamp = 0; /* MV file stamp */
137 static int crypto_verify P((struct exten *, struct value *,
139 static int crypto_encrypt P((struct exten *, struct value *,
141 static int crypto_alice P((struct peer *, struct value *));
142 static int crypto_alice2 P((struct peer *, struct value *));
143 static int crypto_alice3 P((struct peer *, struct value *));
144 static int crypto_bob P((struct exten *, struct value *));
145 static int crypto_bob2 P((struct exten *, struct value *));
146 static int crypto_bob3 P((struct exten *, struct value *));
147 static int crypto_iff P((struct exten *, struct peer *));
148 static int crypto_gq P((struct exten *, struct peer *));
149 static int crypto_mv P((struct exten *, struct peer *));
150 static u_int crypto_send P((struct exten *, struct value *));
151 static tstamp_t crypto_time P((void));
152 static u_long asn2ntp P((ASN1_TIME *));
153 static struct cert_info *cert_parse P((u_char *, u_int, tstamp_t));
154 static int cert_sign P((struct exten *, struct value *));
155 static int cert_valid P((struct cert_info *, EVP_PKEY *));
156 static int cert_install P((struct exten *, struct peer *));
157 static void cert_free P((struct cert_info *));
158 static EVP_PKEY *crypto_key P((char *, tstamp_t *));
159 static int bighash P((BIGNUM *, BIGNUM *));
160 static struct cert_info *crypto_cert P((char *));
161 static void crypto_tai P((char *));
165 readlink(char * link, char * file, int len) {
171 * session_key - generate session key
173 * This routine generates a session key from the source address,
174 * destination address, key ID and private value. The value of the
175 * session key is the MD5 hash of these values, while the next key ID is
176 * the first four octets of the hash.
178 * Returns the next key ID
182 struct sockaddr_storage *srcadr, /* source address */
183 struct sockaddr_storage *dstadr, /* destination address */
184 keyid_t keyno, /* key ID */
185 keyid_t private, /* private value */
186 u_long lifetime /* key lifetime */
189 EVP_MD_CTX ctx; /* message digest context */
190 u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
191 keyid_t keyid; /* key identifer */
192 u_int32 header[10]; /* data in network byte order */
196 * Generate the session key and key ID. If the lifetime is
197 * greater than zero, install the key and call it trusted.
200 switch(srcadr->ss_family) {
202 header[0] = ((struct sockaddr_in *)srcadr)->sin_addr.s_addr;
203 header[1] = ((struct sockaddr_in *)dstadr)->sin_addr.s_addr;
204 header[2] = htonl(keyno);
205 header[3] = htonl(private);
206 hdlen = 4 * sizeof(u_int32);
209 memcpy(&header[0], &GET_INADDR6(*srcadr),
210 sizeof(struct in6_addr));
211 memcpy(&header[4], &GET_INADDR6(*dstadr),
212 sizeof(struct in6_addr));
213 header[8] = htonl(keyno);
214 header[9] = htonl(private);
215 hdlen = 10 * sizeof(u_int32);
218 EVP_DigestInit(&ctx, EVP_md5());
219 EVP_DigestUpdate(&ctx, (u_char *)header, hdlen);
220 EVP_DigestFinal(&ctx, dgst, &len);
221 memcpy(&keyid, dgst, 4);
222 keyid = ntohl(keyid);
224 MD5auth_setkey(keyno, dgst, len);
225 authtrust(keyno, lifetime);
230 "session_key: %s > %s %08x %08x hash %08x life %lu\n",
231 stoa(srcadr), stoa(dstadr), keyno,
232 private, keyid, lifetime);
239 * make_keylist - generate key list
241 * This routine constructs a pseudo-random sequence by repeatedly
242 * hashing the session key starting from a given source address,
243 * destination address, private value and the next key ID of the
244 * preceeding session key. The last entry on the list is saved along
245 * with its sequence number and public signature.
249 struct peer *peer, /* peer structure pointer */
250 struct interface *dstadr /* interface */
253 EVP_MD_CTX ctx; /* signature context */
254 tstamp_t tstamp; /* NTP timestamp */
255 struct autokey *ap; /* autokey pointer */
256 struct value *vp; /* value pointer */
257 keyid_t keyid = 0; /* next key ID */
258 keyid_t cookie; /* private value */
264 * Allocate the key list if necessary.
266 tstamp = crypto_time();
267 if (peer->keylist == NULL)
268 peer->keylist = emalloc(sizeof(keyid_t) *
272 * Generate an initial key ID which is unique and greater than
276 keyid = (u_long)RANDOM & 0xffffffff;
277 if (keyid <= NTP_MAXKEY)
279 if (authhavekey(keyid))
285 * Generate up to NTP_MAXSESSION session keys. Stop if the
286 * next one would not be unique or not a session key ID or if
287 * it would expire before the next poll. The private value
288 * included in the hash is zero if broadcast mode, the peer
289 * cookie if client mode or the host cookie if symmetric modes.
291 lifetime = min(sys_automax, (unsigned long) NTP_MAXSESSION * (1 <<(peer->kpoll)));
292 if (peer->hmode == MODE_BROADCAST)
295 cookie = peer->pcookie;
296 for (i = 0; i < NTP_MAXSESSION; i++) {
297 peer->keylist[i] = keyid;
299 keyid = session_key(&dstadr->sin, &peer->srcadr, keyid,
301 lifetime -= 1 << peer->kpoll;
302 if (auth_havekey(keyid) || keyid <= NTP_MAXKEY ||
303 lifetime <= (unsigned long)(1 << (peer->kpoll)))
308 * Save the last session key ID, sequence number and timestamp,
309 * then sign these values for later retrieval by the clients. Be
310 * careful not to use invalid key media. Use the public values
311 * timestamp as filestamp.
315 vp->ptr = emalloc(sizeof(struct autokey));
316 ap = (struct autokey *)vp->ptr;
317 ap->seq = htonl(peer->keynumber);
318 ap->key = htonl(keyid);
319 vp->tstamp = htonl(tstamp);
320 vp->fstamp = hostval.tstamp;
321 vp->vallen = htonl(sizeof(struct autokey));
323 if (vp->tstamp != 0) {
325 vp->sig = emalloc(sign_siglen);
326 EVP_SignInit(&ctx, sign_digest);
327 EVP_SignUpdate(&ctx, (u_char *)vp, 12);
328 EVP_SignUpdate(&ctx, vp->ptr, sizeof(struct autokey));
329 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
330 vp->siglen = htonl(len);
332 msyslog(LOG_ERR, "make_keys %s\n",
333 ERR_error_string(ERR_get_error(), NULL));
334 peer->flags |= FLAG_ASSOC;
338 printf("make_keys: %d %08x %08x ts %u fs %u poll %d\n",
339 ntohl(ap->seq), ntohl(ap->key), cookie,
340 ntohl(vp->tstamp), ntohl(vp->fstamp), peer->kpoll);
346 * crypto_recv - parse extension fields
348 * This routine is called when the packet has been matched to an
349 * association and passed sanity, format and MAC checks. We believe the
350 * extension field values only if the field has proper format and
351 * length, the timestamp and filestamp are valid and the signature has
352 * valid length and is verified. There are a few cases where some values
353 * are believed even if the signature fails, but only if the proventic
358 struct peer *peer, /* peer structure pointer */
359 struct recvbuf *rbufp /* packet buffer pointer */
362 const EVP_MD *dp; /* message digest algorithm */
363 u_int32 *pkt; /* receive packet pointer */
364 struct autokey *ap, *bp; /* autokey pointer */
365 struct exten *ep, *fp; /* extension pointers */
366 int has_mac; /* length of MAC field */
367 int authlen; /* offset of MAC field */
368 associd_t associd; /* association ID */
369 tstamp_t tstamp = 0; /* timestamp */
370 tstamp_t fstamp = 0; /* filestamp */
371 u_int len; /* extension field length */
372 u_int code; /* extension field opcode */
373 u_int vallen = 0; /* value length */
374 X509 *cert; /* X509 certificate */
375 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
376 keyid_t cookie; /* crumbles */
382 struct timex ntv; /* kernel interface structure */
384 #endif /* KERNEL_PLL */
387 * Initialize. Note that the packet has already been checked for
388 * valid format and extension field lengths. First extract the
389 * field length, command code and association ID in host byte
390 * order. These are used with all commands and modes. Then check
391 * the version number, which must be 2, and length, which must
392 * be at least 8 for requests and VALUE_LEN (24) for responses.
393 * Packets that fail either test sink without a trace. The
394 * association ID is saved only if nonzero.
396 authlen = LEN_PKT_NOMAC;
397 while ((has_mac = rbufp->recv_length - authlen) > MAX_MAC_LEN) {
398 pkt = (u_int32 *)&rbufp->recv_pkt + authlen / 4;
399 ep = (struct exten *)pkt;
400 code = ntohl(ep->opcode) & 0xffff0000;
401 len = ntohl(ep->opcode) & 0x0000ffff;
402 associd = (associd_t) ntohl(pkt[1]);
407 "crypto_recv: flags 0x%x ext offset %d len %u code %x assocID %d\n",
408 peer->crypto, authlen, len, code >> 16,
413 * Check version number and field length. If bad,
414 * quietly ignore the packet.
416 if (((code >> 24) & 0x3f) != CRYPTO_VN || len < 8 ||
417 (len < VALUE_LEN && (code & CRYPTO_RESP))) {
418 sys_unknownversion++;
419 code |= CRYPTO_ERROR;
423 * Little vulnerability bandage here. If a perp tosses a
424 * fake association ID over the fence, we better toss it
425 * out. Only the first one counts.
427 if (code & CRYPTO_RESP) {
428 if (peer->assoc == 0)
429 peer->assoc = associd;
430 else if (peer->assoc != associd)
431 code |= CRYPTO_ERROR;
433 if (len >= VALUE_LEN) {
434 tstamp = ntohl(ep->tstamp);
435 fstamp = ntohl(ep->fstamp);
436 vallen = ntohl(ep->vallen);
441 * Install status word, host name, signature scheme and
442 * association ID. In OpenSSL the signature algorithm is
443 * bound to the digest algorithm, so the NID completely
444 * defines the signature scheme. Note the request and
445 * response are identical, but neither is validated by
446 * signature. The request is processed here only in
447 * symmetric modes. The server name field would be
448 * useful to implement access controls in future.
453 * Pass the extension field to the transmit
458 temp32 = CRYPTO_RESP;
459 fp->opcode |= htonl(temp32);
463 case CRYPTO_ASSOC | CRYPTO_RESP:
466 * Discard the message if it has already been
467 * stored or the server is not synchronized.
469 if (peer->crypto || !fstamp)
472 if (len < VALUE_LEN + vallen) {
478 * Check the identity schemes are compatible. If
479 * the client has PC, the server must have PC,
480 * in which case the server public key and
481 * identity are presumed valid, so we skip the
482 * certificate and identity exchanges and move
483 * immediately to the cookie exchange which
484 * confirms the server signature. If the client
485 * has IFF or GC or both, the server must have
486 * the same one or both. Otherwise, the default
489 if (crypto_flags & CRYPTO_FLAG_PRIV) {
490 if (!(fstamp & CRYPTO_FLAG_PRIV))
493 fstamp |= CRYPTO_FLAG_VALID |
495 } else if (crypto_flags & CRYPTO_FLAG_MASK &&
496 !(crypto_flags & fstamp &
502 * Discard the message if identity error.
504 if (rval != XEVNT_OK)
508 * Discard the message if the host name length
509 * is unreasonable or the signature digest NID
512 temp32 = (fstamp >> 16) & 0xffff;
514 (const EVP_MD *)EVP_get_digestbynid(temp32);
515 if (vallen == 0 || vallen > MAXHOSTNAME)
519 if (rval != XEVNT_OK)
523 * Save status word, host name and message
524 * digest/signature type. If PC identity, be
525 * sure not to sign the certificate.
527 if (crypto_flags & CRYPTO_FLAG_PRIV)
528 fstamp |= CRYPTO_FLAG_SIGN;
529 peer->crypto = fstamp;
531 peer->subject = emalloc(vallen + 1);
532 memcpy(peer->subject, ep->pkt, vallen);
533 peer->subject[vallen] = '\0';
534 peer->issuer = emalloc(vallen + 1);
535 strcpy(peer->issuer, peer->subject);
536 temp32 = (fstamp >> 16) & 0xffff;
538 "flags 0x%x host %s signature %s", fstamp,
539 peer->subject, OBJ_nid2ln(temp32));
540 record_crypto_stats(&peer->srcadr, statstr);
543 printf("crypto_recv: %s\n", statstr);
548 * Decode X509 certificate in ASN.1 format and extract
549 * the data containing, among other things, subject
550 * name and public key. In the default identification
551 * scheme, the certificate trail is followed to a self
552 * signed trusted certificate.
554 case CRYPTO_CERT | CRYPTO_RESP:
557 * Discard the message if invalid or identity
560 if (peer->crypto & CRYPTO_FLAG_VRFY)
563 if ((rval = crypto_verify(ep, NULL, peer)) !=
568 * Scan the certificate list to delete old
569 * versions and link the newest version first on
572 if ((rval = cert_install(ep, peer)) != XEVNT_OK)
576 * If we snatch the certificate before the
577 * server certificate has been signed by its
578 * server, it will be self signed. When it is,
579 * we chase the certificate issuer, which the
580 * server has, and keep going until a self
581 * signed trusted certificate is found. Be sure
582 * to update the issuer field, since it may
585 if (peer->issuer != NULL)
587 peer->issuer = emalloc(strlen(cinfo->issuer) +
589 strcpy(peer->issuer, cinfo->issuer);
592 * We plug in the public key and group key in
593 * the first certificate received. However, note
594 * that this certificate might not be signed by
595 * the server, so we can't check the
596 * signature/digest NID.
598 if (peer->pkey == NULL) {
599 ptr = (u_char *)cinfo->cert.ptr;
600 cert = d2i_X509(NULL, &ptr,
601 ntohl(cinfo->cert.vallen));
602 peer->pkey = X509_get_pubkey(cert);
605 peer->flash &= ~TEST10;
607 sprintf(statstr, "cert %s 0x%x %s (%u) fs %u",
608 cinfo->subject, cinfo->flags,
609 OBJ_nid2ln(temp32), temp32,
611 record_crypto_stats(&peer->srcadr, statstr);
614 printf("crypto_recv: %s\n", statstr);
619 * Schnorr (IFF)identity scheme. This scheme is designed
620 * for use with shared secret group keys and where the
621 * certificate may be generated by a third party. The
622 * client sends a challenge to the server, which
623 * performs a calculation and returns the result. A
624 * positive result is possible only if both client and
625 * server contain the same secret group key.
627 case CRYPTO_IFF | CRYPTO_RESP:
630 * Discard the message if invalid or identity
633 if (peer->crypto & CRYPTO_FLAG_VRFY)
636 if ((rval = crypto_verify(ep, NULL, peer)) !=
641 * If the the challenge matches the response,
642 * the certificate public key, as well as the
643 * server public key, signatyre and identity are
644 * all verified at the same time. The server is
645 * declared trusted, so we skip further
646 * certificate stages and move immediately to
649 if ((rval = crypto_iff(ep, peer)) != XEVNT_OK)
652 peer->crypto |= CRYPTO_FLAG_VRFY |
654 peer->flash &= ~TEST10;
655 sprintf(statstr, "iff fs %u",
657 record_crypto_stats(&peer->srcadr, statstr);
660 printf("crypto_recv: %s\n", statstr);
665 * Guillou-Quisquater (GQ) identity scheme. This scheme
666 * is designed for use with public certificates carrying
667 * the GQ public key in an extension field. The client
668 * sends a challenge to the server, which performs a
669 * calculation and returns the result. A positive result
670 * is possible only if both client and server contain
671 * the same group key and the server has the matching GQ
674 case CRYPTO_GQ | CRYPTO_RESP:
677 * Discard the message if invalid or identity
680 if (peer->crypto & CRYPTO_FLAG_VRFY)
683 if ((rval = crypto_verify(ep, NULL, peer)) !=
688 * If the the challenge matches the response,
689 * the certificate public key, as well as the
690 * server public key, signatyre and identity are
691 * all verified at the same time. The server is
692 * declared trusted, so we skip further
693 * certificate stages and move immediately to
696 if ((rval = crypto_gq(ep, peer)) != XEVNT_OK)
699 peer->crypto |= CRYPTO_FLAG_VRFY |
701 peer->flash &= ~TEST10;
702 sprintf(statstr, "gq fs %u",
704 record_crypto_stats(&peer->srcadr, statstr);
707 printf("crypto_recv: %s\n", statstr);
714 case CRYPTO_MV | CRYPTO_RESP:
717 * Discard the message if invalid or identity
720 if (peer->crypto & CRYPTO_FLAG_VRFY)
723 if ((rval = crypto_verify(ep, NULL, peer)) !=
728 * If the the challenge matches the response,
729 * the certificate public key, as well as the
730 * server public key, signatyre and identity are
731 * all verified at the same time. The server is
732 * declared trusted, so we skip further
733 * certificate stages and move immediately to
736 if ((rval = crypto_mv(ep, peer)) != XEVNT_OK)
739 peer->crypto |= CRYPTO_FLAG_VRFY |
741 peer->flash &= ~TEST10;
742 sprintf(statstr, "mv fs %u",
744 record_crypto_stats(&peer->srcadr, statstr);
747 printf("crypto_recv: %s\n", statstr);
752 * X509 certificate sign response. Validate the
753 * certificate signed by the server and install. Later
754 * this can be provided to clients of this server in
755 * lieu of the self signed certificate in order to
756 * validate the public key.
758 case CRYPTO_SIGN | CRYPTO_RESP:
761 * Discard the message if invalid or identity
764 if (!(peer->crypto & CRYPTO_FLAG_VRFY))
767 if ((rval = crypto_verify(ep, NULL, peer)) !=
772 * Scan the certificate list to delete old
773 * versions and link the newest version first on
776 if ((rval = cert_install(ep, peer)) != XEVNT_OK) break;
778 peer->crypto |= CRYPTO_FLAG_SIGN;
779 peer->flash &= ~TEST10;
781 sprintf(statstr, "sign %s 0x%x %s (%u) fs %u",
782 cinfo->issuer, cinfo->flags,
783 OBJ_nid2ln(temp32), temp32,
785 record_crypto_stats(&peer->srcadr, statstr);
788 printf("crypto_recv: %s\n", statstr);
793 * Cookie request in symmetric modes. Roll a random
794 * cookie and install in symmetric mode. Encrypt for the
795 * response, which is transmitted later.
800 * Discard the message if invalid or identity
803 if (!(peer->crypto & CRYPTO_FLAG_VRFY))
806 if ((rval = crypto_verify(ep, NULL, peer)) !=
811 * Pass the extension field to the transmit
812 * side. If already agreed, walk away.
816 temp32 = CRYPTO_RESP;
817 fp->opcode |= htonl(temp32);
819 if (peer->crypto & CRYPTO_FLAG_AGREE) {
820 peer->flash &= ~TEST10;
825 * Install cookie values and light the cookie
826 * bit. The transmit side will pick up and
827 * encrypt it for the response.
830 peer->cookval.tstamp = ep->tstamp;
831 peer->cookval.fstamp = ep->fstamp;
832 RAND_bytes((u_char *)&peer->pcookie, 4);
833 peer->crypto &= ~CRYPTO_FLAG_AUTO;
834 peer->crypto |= CRYPTO_FLAG_AGREE;
835 peer->flash &= ~TEST10;
836 sprintf(statstr, "cook %x ts %u fs %u",
837 peer->pcookie, ntohl(ep->tstamp),
839 record_crypto_stats(&peer->srcadr, statstr);
842 printf("crypto_recv: %s\n", statstr);
847 * Cookie response in client and symmetric modes. If the
848 * cookie bit is set, the working cookie is the EXOR of
849 * the current and new values.
851 case CRYPTO_COOK | CRYPTO_RESP:
854 * Discard the message if invalid or identity
855 * not confirmed or signature not verified with
856 * respect to the cookie values.
858 if (!(peer->crypto & CRYPTO_FLAG_VRFY))
861 if ((rval = crypto_verify(ep, &peer->cookval,
866 * Decrypt the cookie, hunting all the time for
869 if (vallen == (u_int) EVP_PKEY_size(host_pkey)) {
870 RSA_private_decrypt(vallen,
874 RSA_PKCS1_OAEP_PADDING);
875 cookie = ntohl(temp32);
882 * Install cookie values and light the cookie
883 * bit. If this is not broadcast client mode, we
887 peer->cookval.tstamp = ep->tstamp;
888 peer->cookval.fstamp = ep->fstamp;
889 if (peer->crypto & CRYPTO_FLAG_AGREE)
890 peer->pcookie ^= cookie;
892 peer->pcookie = cookie;
893 if (peer->hmode == MODE_CLIENT &&
894 !(peer->cast_flags & MDF_BCLNT))
895 peer->crypto |= CRYPTO_FLAG_AUTO;
897 peer->crypto &= ~CRYPTO_FLAG_AUTO;
898 peer->crypto |= CRYPTO_FLAG_AGREE;
899 peer->flash &= ~TEST10;
900 sprintf(statstr, "cook %x ts %u fs %u",
901 peer->pcookie, ntohl(ep->tstamp),
903 record_crypto_stats(&peer->srcadr, statstr);
906 printf("crypto_recv: %s\n", statstr);
911 * Install autokey values in broadcast client and
912 * symmetric modes. We have to do this every time the
913 * sever/peer cookie changes or a new keylist is
914 * rolled. Ordinarily, this is automatic as this message
915 * is piggybacked on the first NTP packet sent upon
916 * either of these events. Note that a broadcast client
917 * or symmetric peer can receive this response without a
920 case CRYPTO_AUTO | CRYPTO_RESP:
923 * Discard the message if invalid or identity
924 * not confirmed or signature not verified with
925 * respect to the receive autokey values.
927 if (!(peer->crypto & CRYPTO_FLAG_VRFY))
930 if ((rval = crypto_verify(ep, &peer->recval,
935 * Install autokey values and light the
936 * autokey bit. This is not hard.
938 if (peer->recval.ptr == NULL)
940 emalloc(sizeof(struct autokey));
941 bp = (struct autokey *)peer->recval.ptr;
942 peer->recval.tstamp = ep->tstamp;
943 peer->recval.fstamp = ep->fstamp;
944 ap = (struct autokey *)ep->pkt;
945 bp->seq = ntohl(ap->seq);
946 bp->key = ntohl(ap->key);
947 peer->pkeyid = bp->key;
948 peer->crypto |= CRYPTO_FLAG_AUTO;
949 peer->flash &= ~TEST10;
951 "auto seq %d key %x ts %u fs %u", bp->seq,
952 bp->key, ntohl(ep->tstamp),
954 record_crypto_stats(&peer->srcadr, statstr);
957 printf("crypto_recv: %s\n", statstr);
962 * Install leapseconds table in symmetric modes. This
963 * table is proventicated to the NIST primary servers,
964 * either by copying the file containing the table from
965 * a NIST server to a trusted server or directly using
966 * this protocol. While the entire table is installed at
967 * the server, presently only the current TAI offset is
968 * provided via the kernel to other applications.
973 * Discard the message if invalid or identity
976 if (!(peer->crypto & CRYPTO_FLAG_VRFY))
979 if ((rval = crypto_verify(ep, NULL, peer)) !=
984 * Pass the extension field to the transmit
985 * side. Continue below if a leapseconds table
986 * accompanies the message.
990 temp32 = CRYPTO_RESP;
991 fp->opcode |= htonl(temp32);
993 if (len <= VALUE_LEN) {
994 peer->flash &= ~TEST10;
999 case CRYPTO_TAI | CRYPTO_RESP:
1002 * Discard the message if invalid or identity
1003 * not confirmed or signature not verified with
1004 * respect to the leapsecond table values.
1006 if (!(peer->crypto & CRYPTO_FLAG_VRFY))
1009 if ((rval = crypto_verify(ep, &peer->tai_leap,
1014 * Initialize peer variables, leapseconds
1015 * structure and extension field in network byte
1016 * order. Since a filestamp may have changed,
1017 * recompute the signatures.
1019 peer->tai_leap.tstamp = ep->tstamp;
1020 peer->tai_leap.fstamp = ep->fstamp;
1021 peer->tai_leap.vallen = ep->vallen;
1024 * Install the new table if there is no stored
1025 * table or the new table is more recent than
1026 * the stored table. Since a filestamp may have
1027 * changed, recompute the signatures.
1029 if (ntohl(peer->tai_leap.fstamp) >
1030 ntohl(tai_leap.fstamp)) {
1031 tai_leap.fstamp = ep->fstamp;
1032 tai_leap.vallen = ep->vallen;
1033 if (tai_leap.ptr != NULL)
1035 tai_leap.ptr = emalloc(vallen);
1036 memcpy(tai_leap.ptr, ep->pkt, vallen);
1038 sys_tai = vallen / 4 + TAI_1972 - 1;
1040 crypto_flags |= CRYPTO_FLAG_TAI;
1041 peer->crypto |= CRYPTO_FLAG_LEAP;
1042 peer->flash &= ~TEST10;
1046 * If the kernel cooperates, initialize the
1047 * current TAI offset.
1049 ntv.modes = MOD_TAI;
1050 ntv.constant = sys_tai;
1051 (void)ntp_adjtime(&ntv);
1052 #endif /* NTP_API */
1053 #endif /* KERNEL_PLL */
1054 sprintf(statstr, "leap %u ts %u fs %u",
1055 vallen, ntohl(ep->tstamp),
1057 record_crypto_stats(&peer->srcadr, statstr);
1060 printf("crypto_recv: %s\n", statstr);
1065 * We come here in symmetric modes for miscellaneous
1066 * commands that have value fields but are processed on
1067 * the transmit side. All we need do here is check for
1068 * valid field length. Remaining checks are below and on
1069 * the transmit side.
1075 if (len < VALUE_LEN) {
1083 * We come here for miscellaneous requests and unknown
1084 * requests and responses. If an unknown response or
1085 * error, forget it. If a request, save the extension
1086 * field for later. Unknown requests will be caught on
1087 * the transmit side.
1090 if (code & (CRYPTO_RESP | CRYPTO_ERROR)) {
1092 } else if ((rval = crypto_verify(ep, NULL,
1093 peer)) == XEVNT_OK) {
1095 memcpy(fp, ep, len);
1096 temp32 = CRYPTO_RESP;
1097 fp->opcode |= htonl(temp32);
1103 * We log everything except length/format errors and
1104 * duplicates, which are log clogging vulnerabilities.
1105 * The first error found terminates the extension field
1106 * scan and we return the laundry to the caller.
1108 if (rval != XEVNT_OK) {
1110 "error %x opcode %x ts %u fs %u", rval,
1111 code, tstamp, fstamp);
1112 if (rval > XEVNT_TSP)
1113 record_crypto_stats(&peer->srcadr,
1115 report_event(rval, peer);
1118 printf("crypto_recv: %s\n", statstr);
1129 * crypto_xmit - construct extension fields
1131 * This routine is called both when an association is configured and
1132 * when one is not. The only case where this matters is to retrieve the
1133 * autokey information, in which case the caller has to provide the
1134 * association ID to match the association.
1136 * Returns length of extension field.
1140 struct pkt *xpkt, /* transmit packet pointer */
1141 struct sockaddr_storage *srcadr_sin, /* active runway */
1142 int start, /* offset to extension field */
1143 struct exten *ep, /* extension pointer */
1144 keyid_t cookie /* session cookie */
1147 u_int32 *pkt; /* packet pointer */
1148 struct peer *peer; /* peer structure pointer */
1149 u_int opcode; /* extension field opcode */
1150 struct exten *fp; /* extension pointers */
1151 struct cert_info *cp; /* certificate info/value pointer */
1152 char certname[MAXHOSTNAME + 1]; /* subject name buffer */
1153 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1162 * Generate the requested extension field request code, length
1163 * and association ID. If this is a response and the host is not
1164 * synchronized, light the error bit and go home.
1166 pkt = (u_int32 *)xpkt + start / 4;
1167 fp = (struct exten *)pkt;
1168 opcode = ntohl(ep->opcode);
1169 associd = (associd_t) ntohl(ep->associd);
1170 fp->associd = htonl(associd);
1173 switch (opcode & 0xffff0000) {
1176 * Send association request and response with status word and
1177 * host name. Note, this message is not signed and the filestamp
1178 * contains only the status word. We check at this point whether
1179 * the identity schemes are compatible to save tears later on.
1181 case CRYPTO_ASSOC | CRYPTO_RESP:
1183 len += crypto_send(fp, &hostval);
1184 if (crypto_time() == 0)
1187 fp->fstamp = htonl(crypto_flags);
1191 * Send certificate request. Use the values from the extension
1195 memset(&vtemp, 0, sizeof(vtemp));
1196 vtemp.tstamp = ep->tstamp;
1197 vtemp.fstamp = ep->fstamp;
1198 vtemp.vallen = ep->vallen;
1199 vtemp.ptr = (unsigned char *)ep->pkt;
1200 len += crypto_send(fp, &vtemp);
1204 * Send certificate response or sign request. Use the values
1205 * from the certificate. If the request contains no subject
1206 * name, assume the name of this host. This is for backwards
1207 * compatibility. Light the error bit if no certificate with
1208 * the given subject name is found. Of course, private
1209 * certificates are never sent.
1212 case CRYPTO_CERT | CRYPTO_RESP:
1213 vallen = ntohl(ep->vallen);
1215 strcpy(certname, sys_hostname);
1216 } else if (vallen == 0 || vallen > MAXHOSTNAME) {
1217 opcode |= CRYPTO_ERROR;
1221 memcpy(certname, ep->pkt, vallen);
1222 certname[vallen] = '\0';
1224 for (cp = cinfo; cp != NULL; cp = cp->link) {
1225 if (cp->flags & CERT_PRIV)
1227 if (strcmp(certname, cp->subject) == 0) {
1228 len += crypto_send(fp, &cp->cert);
1233 opcode |= CRYPTO_ERROR;
1237 * Send challenge in Schnorr (IFF) identity scheme.
1240 if ((peer = findpeerbyassoc(ep->pkt[0])) == NULL) {
1241 opcode |= CRYPTO_ERROR;
1244 if ((rval = crypto_alice(peer, &vtemp)) == XEVNT_OK)
1245 len += crypto_send(fp, &vtemp);
1250 * Send response in Schnorr (IFF) identity scheme.
1252 case CRYPTO_IFF | CRYPTO_RESP:
1253 if ((rval = crypto_bob(ep, &vtemp)) == XEVNT_OK)
1254 len += crypto_send(fp, &vtemp);
1259 * Send challenge in Guillou-Quisquater (GQ) identity scheme.
1262 if ((peer = findpeerbyassoc(ep->pkt[0])) == NULL) {
1263 opcode |= CRYPTO_ERROR;
1266 if ((rval = crypto_alice2(peer, &vtemp)) == XEVNT_OK)
1267 len += crypto_send(fp, &vtemp);
1272 * Send response in Guillou-Quisquater (GQ) identity scheme.
1274 case CRYPTO_GQ | CRYPTO_RESP:
1275 if ((rval = crypto_bob2(ep, &vtemp)) == XEVNT_OK)
1276 len += crypto_send(fp, &vtemp);
1281 * Send challenge in MV identity scheme.
1284 if ((peer = findpeerbyassoc(ep->pkt[0])) == NULL) {
1285 opcode |= CRYPTO_ERROR;
1288 if ((rval = crypto_alice3(peer, &vtemp)) == XEVNT_OK)
1289 len += crypto_send(fp, &vtemp);
1294 * Send response in MV identity scheme.
1296 case CRYPTO_MV | CRYPTO_RESP:
1297 if ((rval = crypto_bob3(ep, &vtemp)) == XEVNT_OK)
1298 len += crypto_send(fp, &vtemp);
1303 * Send certificate sign response. The integrity of the request
1304 * certificate has already been verified on the receive side.
1305 * Sign the response using the local server key. Use the
1306 * filestamp from the request and use the timestamp as the
1307 * current time. Light the error bit if the certificate is
1308 * invalid or contains an unverified signature.
1310 case CRYPTO_SIGN | CRYPTO_RESP:
1311 if ((rval = cert_sign(ep, &vtemp)) == XEVNT_OK)
1312 len += crypto_send(fp, &vtemp);
1317 * Send public key and signature. Use the values from the public
1321 len += crypto_send(fp, &pubkey);
1325 * Encrypt and send cookie and signature. Light the error bit if
1326 * anything goes wrong.
1328 case CRYPTO_COOK | CRYPTO_RESP:
1329 if ((opcode & 0xffff) < VALUE_LEN) {
1330 opcode |= CRYPTO_ERROR;
1333 if (PKT_MODE(xpkt->li_vn_mode) == MODE_SERVER) {
1336 if ((peer = findpeerbyassoc(associd)) == NULL) {
1337 opcode |= CRYPTO_ERROR;
1340 tcookie = peer->pcookie;
1342 if ((rval = crypto_encrypt(ep, &vtemp, &tcookie)) ==
1344 len += crypto_send(fp, &vtemp);
1349 * Find peer and send autokey data and signature in broadcast
1350 * server and symmetric modes. Use the values in the autokey
1351 * structure. If no association is found, either the server has
1352 * restarted with new associations or some perp has replayed an
1353 * old message, in which case light the error bit.
1355 case CRYPTO_AUTO | CRYPTO_RESP:
1356 if ((peer = findpeerbyassoc(associd)) == NULL) {
1357 opcode |= CRYPTO_ERROR;
1360 peer->flags &= ~FLAG_ASSOC;
1361 len += crypto_send(fp, &peer->sndval);
1365 * Send leapseconds table and signature. Use the values from the
1366 * tai structure. If no table has been loaded, just send a
1370 case CRYPTO_TAI | CRYPTO_RESP:
1371 if (crypto_flags & CRYPTO_FLAG_TAI)
1372 len += crypto_send(fp, &tai_leap);
1376 * Default - Fall through for requests; for unknown responses,
1380 if (opcode & CRYPTO_RESP)
1381 opcode |= CRYPTO_ERROR;
1385 * We ignore length/format errors and duplicates. Other errors
1386 * are reported to the log and deny further service. To really
1387 * persistent rascals we toss back a kiss-of-death grenade.
1389 if (rval > XEVNT_TSP) {
1390 opcode |= CRYPTO_ERROR;
1391 sprintf(statstr, "error %x opcode %x", rval, opcode);
1392 record_crypto_stats(srcadr_sin, statstr);
1395 printf("crypto_xmit: %s\n", statstr);
1400 * Round up the field length to a multiple of 8 bytes and save
1401 * the request code and length.
1403 len = ((len + 7) / 8) * 8;
1404 fp->opcode = htonl((opcode & 0xffff0000) | len);
1408 "crypto_xmit: ext offset %d len %u code %x assocID %d\n",
1409 start, len, opcode>> 16, associd);
1416 * crypto_verify - parse and verify the extension field and value
1420 * XEVNT_LEN bad field format or length
1421 * XEVNT_TSP bad timestamp
1422 * XEVNT_FSP bad filestamp
1423 * XEVNT_PUB bad or missing public key
1424 * XEVNT_SGL bad signature length
1425 * XEVNT_SIG signature not verified
1429 struct exten *ep, /* extension pointer */
1430 struct value *vp, /* value pointer */
1431 struct peer *peer /* peer structure pointer */
1434 EVP_PKEY *pkey; /* server public key */
1435 EVP_MD_CTX ctx; /* signature context */
1436 tstamp_t tstamp; /* timestamp */
1437 tstamp_t fstamp; /* filestamp */
1438 u_int vallen; /* value length */
1439 u_int siglen; /* signature length */
1445 * We require valid opcode and field length, timestamp,
1446 * filestamp, public key, digest, signature length and
1447 * signature, where relevant. Note that preliminary length
1448 * checks are done in the main loop.
1450 len = ntohl(ep->opcode) & 0x0000ffff;
1451 opcode = ntohl(ep->opcode) & 0xffff0000;
1454 * Check for valid operation code and protocol. The opcode must
1455 * not have the error bit set. If a response, it must have a
1456 * value header. If a request and does not contain a value
1457 * header, no need for further checking.
1459 if (opcode & CRYPTO_ERROR)
1461 if (opcode & CRYPTO_RESP) {
1462 if (len < VALUE_LEN)
1465 if (len < VALUE_LEN)
1469 * We have a value header. Check for valid field lengths. The
1470 * field length must be long enough to contain the value header,
1471 * value and signature. If a request and a previous request of
1472 * the same type is pending, discard the previous request. If a
1473 * request but no signature, there is no need for further
1476 vallen = ntohl(ep->vallen);
1477 if (len < ((VALUE_LEN + vallen + 3) / 4) * 4)
1480 i = (vallen + 3) / 4;
1481 siglen = ntohl(ep->pkt[i++]);
1482 if (len < VALUE_LEN + vallen + siglen)
1485 if (!(opcode & CRYPTO_RESP)) {
1486 if (peer->cmmd != NULL) {
1487 if ((opcode | CRYPTO_RESP) ==
1488 (ntohl(peer->cmmd->opcode) & 0xffff0000)) {
1500 * We have a signature. Check for valid timestamp and filestamp.
1501 * The timestamp must not precede the filestamp. The timestamp
1502 * and filestamp must not precede the corresponding values in
1503 * the value structure. Once the autokey values have been
1504 * installed, the timestamp must always be later than the
1505 * corresponding value in the value structure. Duplicate
1506 * timestamps are illegal once the cookie has been validated.
1509 if (crypto_flags & peer->crypto & CRYPTO_FLAG_PRIV)
1513 tstamp = ntohl(ep->tstamp);
1514 fstamp = ntohl(ep->fstamp);
1515 if (tstamp == 0 || tstamp < fstamp) {
1517 } else if (vp != NULL && (tstamp < ntohl(vp->tstamp) ||
1518 (tstamp == ntohl(vp->tstamp) && (peer->crypto &
1519 CRYPTO_FLAG_AUTO)))) {
1521 } else if (vp != NULL && (tstamp < ntohl(vp->fstamp) || fstamp <
1522 ntohl(vp->fstamp))) {
1526 * If a public key and digest is present, and if valid key
1527 * length, check for valid signature. Note that the first valid
1528 * signature lights the proventic bit.
1530 } else if (pkey == NULL || peer->digest == NULL) {
1532 } else if (siglen != (u_int) EVP_PKEY_size(pkey)) {
1535 EVP_VerifyInit(&ctx, peer->digest);
1536 EVP_VerifyUpdate(&ctx, (u_char *)&ep->tstamp, vallen +
1538 if (EVP_VerifyFinal(&ctx, (u_char *)&ep->pkt[i], siglen,
1540 if (peer->crypto & CRYPTO_FLAG_VRFY)
1541 peer->crypto |= CRYPTO_FLAG_PROV;
1549 "crypto_recv: verify %x vallen %u siglen %u ts %u fs %u\n",
1550 rval, vallen, siglen, tstamp, fstamp);
1557 * crypto_encrypt - construct encrypted cookie and signature from
1558 * extension field and cookie
1562 * XEVNT_PUB bad or missing public key
1563 * XEVNT_CKY bad or missing cookie
1567 struct exten *ep, /* extension pointer */
1568 struct value *vp, /* value pointer */
1569 keyid_t *cookie /* server cookie */
1572 EVP_PKEY *pkey; /* public key */
1573 EVP_MD_CTX ctx; /* signature context */
1574 tstamp_t tstamp; /* NTP timestamp */
1580 * Extract the public key from the request.
1582 len = ntohl(ep->vallen);
1583 ptr = (u_char *)ep->pkt;
1584 pkey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &ptr, len);
1586 msyslog(LOG_ERR, "crypto_encrypt %s\n",
1587 ERR_error_string(ERR_get_error(), NULL));
1592 * Encrypt the cookie, encode in ASN.1 and sign.
1594 tstamp = crypto_time();
1595 memset(vp, 0, sizeof(struct value));
1596 vp->tstamp = htonl(tstamp);
1597 vp->fstamp = hostval.tstamp;
1598 len = EVP_PKEY_size(pkey);
1599 vp->vallen = htonl(len);
1600 vp->ptr = emalloc(len);
1601 temp32 = htonl(*cookie);
1602 if (!RSA_public_encrypt(4, (u_char *)&temp32, vp->ptr,
1603 pkey->pkey.rsa, RSA_PKCS1_OAEP_PADDING)) {
1604 msyslog(LOG_ERR, "crypto_encrypt %s\n",
1605 ERR_error_string(ERR_get_error(), NULL));
1606 EVP_PKEY_free(pkey);
1609 EVP_PKEY_free(pkey);
1613 vp->sig = emalloc(sign_siglen);
1614 EVP_SignInit(&ctx, sign_digest);
1615 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
1616 EVP_SignUpdate(&ctx, vp->ptr, len);
1617 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
1618 vp->siglen = htonl(len);
1624 * crypto_ident - construct extension field for identity scheme
1626 * This routine determines which identity scheme is in use and
1627 * constructs an extension field for that scheme.
1631 struct peer *peer /* peer structure pointer */
1634 char filename[MAXFILENAME + 1];
1637 * If the server identity has already been verified, no further
1638 * action is necessary. Otherwise, try to load the identity file
1639 * of the certificate issuer. If the issuer file is not found,
1640 * try the host file. If nothing found, declare a cryptobust.
1641 * Note we can't get here unless the trusted certificate has
1642 * been found and the CRYPTO_FLAG_VALID bit is set, so the
1643 * certificate issuer is valid.
1645 if (peer->crypto & CRYPTO_FLAG_VRFY)
1648 if (peer->ident_pkey != NULL)
1649 EVP_PKEY_free(peer->ident_pkey);
1650 if (peer->crypto & CRYPTO_FLAG_GQ) {
1651 snprintf(filename, MAXFILENAME, "ntpkey_gq_%s",
1653 peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1654 if (peer->ident_pkey != NULL)
1657 snprintf(filename, MAXFILENAME, "ntpkey_gq_%s",
1659 peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1660 if (peer->ident_pkey != NULL)
1663 if (peer->crypto & CRYPTO_FLAG_IFF) {
1664 snprintf(filename, MAXFILENAME, "ntpkey_iff_%s",
1666 peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1667 if (peer->ident_pkey != NULL)
1668 return (CRYPTO_IFF);
1670 snprintf(filename, MAXFILENAME, "ntpkey_iff_%s",
1672 peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1673 if (peer->ident_pkey != NULL)
1674 return (CRYPTO_IFF);
1676 if (peer->crypto & CRYPTO_FLAG_MV) {
1677 snprintf(filename, MAXFILENAME, "ntpkey_mv_%s",
1679 peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1680 if (peer->ident_pkey != NULL)
1683 snprintf(filename, MAXFILENAME, "ntpkey_mv_%s",
1685 peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1686 if (peer->ident_pkey != NULL)
1691 * No compatible identity scheme is available. Use the default
1695 "crypto_ident: no compatible identity scheme found");
1701 * crypto_args - construct extension field from arguments
1703 * This routine creates an extension field with current timestamps and
1704 * specified opcode, association ID and optional string. Note that the
1705 * extension field is created here, but freed after the crypto_xmit()
1706 * call in the protocol module.
1708 * Returns extension field pointer (no errors).
1712 struct peer *peer, /* peer structure pointer */
1713 u_int opcode, /* operation code */
1714 char *str /* argument string */
1717 tstamp_t tstamp; /* NTP timestamp */
1718 struct exten *ep; /* extension field pointer */
1719 u_int len; /* extension field length */
1721 tstamp = crypto_time();
1722 len = sizeof(struct exten);
1727 ep->opcode = htonl(opcode + len);
1730 * If a response, send our ID; if a request, send the
1733 if (opcode & CRYPTO_RESP)
1734 ep->associd = htonl(peer->associd);
1736 ep->associd = htonl(peer->assoc);
1737 ep->tstamp = htonl(tstamp);
1738 ep->fstamp = hostval.tstamp;
1741 ep->vallen = htonl(strlen(str));
1742 memcpy((char *)ep->pkt, str, strlen(str));
1744 ep->pkt[0] = peer->associd;
1751 * crypto_send - construct extension field from value components
1753 * Returns extension field length. Note: it is not polite to send a
1754 * nonempty signature with zero timestamp or a nonzero timestamp with
1755 * empty signature, but these rules are not enforced here.
1759 struct exten *ep, /* extension field pointer */
1760 struct value *vp /* value pointer */
1767 * Copy data. If the data field is empty or zero length, encode
1768 * an empty value with length zero.
1770 ep->tstamp = vp->tstamp;
1771 ep->fstamp = vp->fstamp;
1772 ep->vallen = vp->vallen;
1774 temp32 = ntohl(vp->vallen);
1775 if (temp32 > 0 && vp->ptr != NULL)
1776 memcpy(ep->pkt, vp->ptr, temp32);
1779 * Copy signature. If the signature field is empty or zero
1780 * length, encode an empty signature with length zero.
1782 i = (temp32 + 3) / 4;
1784 ep->pkt[i++] = vp->siglen;
1785 temp32 = ntohl(vp->siglen);
1786 if (temp32 > 0 && vp->sig != NULL)
1787 memcpy(&ep->pkt[i], vp->sig, temp32);
1794 * crypto_update - compute new public value and sign extension fields
1796 * This routine runs periodically, like once a day, and when something
1797 * changes. It updates the timestamps on three value structures and one
1798 * value structure list, then signs all the structures:
1800 * hostval host name (not signed)
1802 * cinfo certificate info/value list
1803 * tai_leap leapseconds file
1805 * Filestamps are proventicated data, so this routine is run only when
1806 * the host has been synchronized to a proventicated source. Thus, the
1807 * timestamp is proventicated, too, and can be used to deflect
1808 * clogging attacks and even cook breakfast.
1810 * Returns void (no errors)
1815 EVP_MD_CTX ctx; /* message digest context */
1816 struct cert_info *cp, *cpn, **zp; /* certificate info/value */
1817 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1818 tstamp_t tstamp; /* NTP timestamp */
1821 if ((tstamp = crypto_time()) == 0)
1823 hostval.tstamp = htonl(tstamp);
1826 * Sign public key and timestamps. The filestamp is derived from
1827 * the host key file extension from wherever the file was
1830 if (pubkey.vallen != 0) {
1831 pubkey.tstamp = hostval.tstamp;
1833 if (pubkey.sig == NULL)
1834 pubkey.sig = emalloc(sign_siglen);
1835 EVP_SignInit(&ctx, sign_digest);
1836 EVP_SignUpdate(&ctx, (u_char *)&pubkey, 12);
1837 EVP_SignUpdate(&ctx, pubkey.ptr, ntohl(pubkey.vallen));
1838 if (EVP_SignFinal(&ctx, pubkey.sig, &len, sign_pkey))
1839 pubkey.siglen = htonl(len);
1843 * Sign certificates and timestamps. The filestamp is derived
1844 * from the certificate file extension from wherever the file
1845 * was generated. At the same time expired certificates are
1849 for (cp = cinfo; cp != NULL; cp = cpn) {
1851 if (tstamp > cp->last) {
1855 cp->cert.tstamp = hostval.tstamp;
1856 cp->cert.siglen = 0;
1857 if (cp->cert.sig == NULL)
1858 cp->cert.sig = emalloc(sign_siglen);
1859 EVP_SignInit(&ctx, sign_digest);
1860 EVP_SignUpdate(&ctx, (u_char *)&cp->cert, 12);
1861 EVP_SignUpdate(&ctx, cp->cert.ptr,
1862 ntohl(cp->cert.vallen));
1863 if (EVP_SignFinal(&ctx, cp->cert.sig, &len,
1865 cp->cert.siglen = htonl(len);
1871 * Sign leapseconds table and timestamps. The filestamp is
1872 * derived from the leapsecond file extension from wherever the
1873 * file was generated.
1875 if (tai_leap.vallen != 0) {
1876 tai_leap.tstamp = hostval.tstamp;
1877 tai_leap.siglen = 0;
1878 if (tai_leap.sig == NULL)
1879 tai_leap.sig = emalloc(sign_siglen);
1880 EVP_SignInit(&ctx, sign_digest);
1881 EVP_SignUpdate(&ctx, (u_char *)&tai_leap, 12);
1882 EVP_SignUpdate(&ctx, tai_leap.ptr,
1883 ntohl(tai_leap.vallen));
1884 if (EVP_SignFinal(&ctx, tai_leap.sig, &len, sign_pkey))
1885 tai_leap.siglen = htonl(len);
1887 sprintf(statstr, "update ts %u", ntohl(hostval.tstamp));
1888 record_crypto_stats(NULL, statstr);
1891 printf("crypto_update: %s\n", statstr);
1897 * value_free - free value structure components.
1899 * Returns void (no errors)
1903 struct value *vp /* value structure */
1906 if (vp->ptr != NULL)
1908 if (vp->sig != NULL)
1910 memset(vp, 0, sizeof(struct value));
1915 * crypto_time - returns current NTP time in seconds.
1920 l_fp tstamp; /* NTP time */ L_CLR(&tstamp);
1923 if (sys_leap != LEAP_NOTINSYNC)
1924 get_systime(&tstamp);
1925 return (tstamp.l_ui);
1930 * asn2ntp - convert ASN1_TIME time structure to NTP time in seconds.
1934 ASN1_TIME *asn1time /* pointer to ASN1_TIME structure */
1937 char *v; /* pointer to ASN1_TIME string */
1938 struct tm tm; /* used to convert to NTP time */
1941 * Extract time string YYMMDDHHMMSSZ from ASN1 time structure.
1942 * Note that the YY, MM, DD fields start with one, the HH, MM,
1943 * SS fiels start with zero and the Z character should be 'Z'
1944 * for UTC. Also note that years less than 50 map to years
1945 * greater than 100. Dontcha love ASN.1? Better than MIL-188.
1947 if (asn1time->length > 13)
1948 return ((u_long)(~0)); /* We can't use -1 here. It's invalid */
1949 v = (char *)asn1time->data;
1950 tm.tm_year = (v[0] - '0') * 10 + v[1] - '0';
1951 if (tm.tm_year < 50)
1953 tm.tm_mon = (v[2] - '0') * 10 + v[3] - '0' - 1;
1954 tm.tm_mday = (v[4] - '0') * 10 + v[5] - '0';
1955 tm.tm_hour = (v[6] - '0') * 10 + v[7] - '0';
1956 tm.tm_min = (v[8] - '0') * 10 + v[9] - '0';
1957 tm.tm_sec = (v[10] - '0') * 10 + v[11] - '0';
1961 return (timegm(&tm) + JAN_1970);
1966 * bigdig() - compute a BIGNUM MD5 hash of a BIGNUM number.
1970 BIGNUM *bn, /* BIGNUM * from */
1971 BIGNUM *bk /* BIGNUM * to */
1974 EVP_MD_CTX ctx; /* message digest context */
1975 u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
1976 u_char *ptr; /* a BIGNUM as binary string */
1979 len = BN_num_bytes(bn);
1982 EVP_DigestInit(&ctx, EVP_md5());
1983 EVP_DigestUpdate(&ctx, ptr, len);
1984 EVP_DigestFinal(&ctx, dgst, &len);
1985 BN_bin2bn(dgst, len, bk);
1991 ***********************************************************************
1993 * The following routines implement the Schnorr (IFF) identity scheme *
1995 ***********************************************************************
1997 * The Schnorr (IFF) identity scheme is intended for use when
1998 * the ntp-genkeys program does not generate the certificates used in
1999 * the protocol and the group key cannot be conveyed in the certificate
2000 * itself. For this purpose, new generations of IFF values must be
2001 * securely transmitted to all members of the group before use. The
2002 * scheme is self contained and independent of new generations of host
2003 * keys, sign keys and certificates.
2005 * The IFF identity scheme is based on DSA cryptography and algorithms
2006 * described in Stinson p. 285. The IFF values hide in a DSA cuckoo
2007 * structure, but only the primes and generator are used. The p is a
2008 * 512-bit prime, q a 160-bit prime that divides p - 1 and is a qth root
2009 * of 1 mod p; that is, g^q = 1 mod p. The TA rolls primvate random
2010 * group key b disguised as a DSA structure member, then computes public
2011 * key g^(q - b). These values are shared only among group members and
2012 * never revealed in messages. Alice challenges Bob to confirm identity
2013 * using the protocol described below.
2017 * The scheme goes like this. Both Alice and Bob have the public primes
2018 * p, q and generator g. The TA gives private key b to Bob and public
2019 * key v = g^(q - a) mod p to Alice.
2021 * Alice rolls new random challenge r and sends to Bob in the IFF
2022 * request message. Bob rolls new random k, then computes y = k + b r
2023 * mod q and x = g^k mod p and sends (y, hash(x)) to Alice in the
2024 * response message. Besides making the response shorter, the hash makes
2025 * it effectivey impossible for an intruder to solve for b by observing
2026 * a number of these messages.
2028 * Alice receives the response and computes g^y v^r mod p. After a bit
2029 * of algebra, this simplifies to g^k. If the hash of this result
2030 * matches hash(x), Alice knows that Bob has the group key b. The signed
2031 * response binds this knowledge to Bob's private key and the public key
2032 * previously received in his certificate.
2034 * crypto_alice - construct Alice's challenge in IFF scheme
2038 * XEVNT_PUB bad or missing public key
2039 * XEVNT_ID bad or missing identity parameters
2043 struct peer *peer, /* peer pointer */
2044 struct value *vp /* value pointer */
2047 DSA *dsa; /* IFF parameters */
2048 BN_CTX *bctx; /* BIGNUM context */
2049 EVP_MD_CTX ctx; /* signature context */
2054 * The identity parameters must have correct format and content.
2056 if (peer->ident_pkey == NULL)
2058 if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
2059 msyslog(LOG_INFO, "crypto_alice: defective key");
2064 * Roll new random r (0 < r < q). The OpenSSL library has a bug
2065 * omitting BN_rand_range, so we have to do it the hard way.
2067 bctx = BN_CTX_new();
2068 len = BN_num_bytes(dsa->q);
2069 if (peer->iffval != NULL)
2070 BN_free(peer->iffval);
2071 peer->iffval = BN_new();
2072 BN_rand(peer->iffval, len * 8, -1, 1); /* r */
2073 BN_mod(peer->iffval, peer->iffval, dsa->q, bctx);
2077 * Sign and send to Bob. The filestamp is from the local file.
2079 tstamp = crypto_time();
2080 memset(vp, 0, sizeof(struct value));
2081 vp->tstamp = htonl(tstamp);
2082 vp->fstamp = htonl(peer->fstamp);
2083 vp->vallen = htonl(len);
2084 vp->ptr = emalloc(len);
2085 BN_bn2bin(peer->iffval, vp->ptr);
2089 vp->sig = emalloc(sign_siglen);
2090 EVP_SignInit(&ctx, sign_digest);
2091 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2092 EVP_SignUpdate(&ctx, vp->ptr, len);
2093 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2094 vp->siglen = htonl(len);
2100 * crypto_bob - construct Bob's response to Alice's challenge
2104 * XEVNT_PUB bad or missing public key
2108 struct exten *ep, /* extension pointer */
2109 struct value *vp /* value pointer */
2112 DSA *dsa; /* IFF parameters */
2113 DSA_SIG *sdsa; /* DSA signature context fake */
2114 BN_CTX *bctx; /* BIGNUM context */
2115 EVP_MD_CTX ctx; /* signature context */
2116 tstamp_t tstamp; /* NTP timestamp */
2117 BIGNUM *bn, *bk, *r;
2122 * If the IFF parameters are not valid, something awful
2123 * happened or we are being tormented.
2125 if (!(crypto_flags & CRYPTO_FLAG_IFF)) {
2126 msyslog(LOG_INFO, "crypto_bob: scheme unavailable");
2129 dsa = iffpar_pkey->pkey.dsa;
2132 * Extract r from the challenge.
2134 len = ntohl(ep->vallen);
2135 if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2136 msyslog(LOG_ERR, "crypto_bob %s\n",
2137 ERR_error_string(ERR_get_error(), NULL));
2142 * Bob rolls random k (0 < k < q), computes y = k + b r mod q
2143 * and x = g^k mod p, then sends (y, hash(x)) to Alice.
2145 bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2146 sdsa = DSA_SIG_new();
2147 BN_rand(bk, len * 8, -1, 1); /* k */
2148 BN_mod_mul(bn, dsa->priv_key, r, dsa->q, bctx); /* b r mod q */
2150 BN_mod(bn, bn, dsa->q, bctx); /* k + b r mod q */
2151 sdsa->r = BN_dup(bn);
2152 BN_mod_exp(bk, dsa->g, bk, dsa->p, bctx); /* g^k mod p */
2154 sdsa->s = BN_dup(bk);
2156 BN_free(r); BN_free(bn); BN_free(bk);
2159 * Encode the values in ASN.1 and sign.
2161 tstamp = crypto_time();
2162 memset(vp, 0, sizeof(struct value));
2163 vp->tstamp = htonl(tstamp);
2164 vp->fstamp = htonl(if_fstamp);
2165 len = i2d_DSA_SIG(sdsa, NULL);
2167 msyslog(LOG_ERR, "crypto_bob %s\n",
2168 ERR_error_string(ERR_get_error(), NULL));
2172 vp->vallen = htonl(len);
2175 i2d_DSA_SIG(sdsa, &ptr);
2180 vp->sig = emalloc(sign_siglen);
2181 EVP_SignInit(&ctx, sign_digest);
2182 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2183 EVP_SignUpdate(&ctx, vp->ptr, len);
2184 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2185 vp->siglen = htonl(len);
2191 * crypto_iff - verify Bob's response to Alice's challenge
2195 * XEVNT_PUB bad or missing public key
2196 * XEVNT_FSP bad filestamp
2197 * XEVNT_ID bad or missing identity parameters
2201 struct exten *ep, /* extension pointer */
2202 struct peer *peer /* peer structure pointer */
2205 DSA *dsa; /* IFF parameters */
2206 BN_CTX *bctx; /* BIGNUM context */
2207 DSA_SIG *sdsa; /* DSA parameters */
2214 * If the IFF parameters are not valid or no challenge was sent,
2215 * something awful happened or we are being tormented.
2217 if (peer->ident_pkey == NULL) {
2218 msyslog(LOG_INFO, "crypto_iff: scheme unavailable");
2221 if (ntohl(ep->fstamp) != peer->fstamp) {
2222 msyslog(LOG_INFO, "crypto_iff: invalid filestamp %u",
2226 if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
2227 msyslog(LOG_INFO, "crypto_iff: defective key");
2230 if (peer->iffval == NULL) {
2231 msyslog(LOG_INFO, "crypto_iff: missing challenge");
2236 * Extract the k + b r and g^k values from the response.
2238 bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2239 len = ntohl(ep->vallen);
2240 ptr = (const u_char *)ep->pkt;
2241 if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2242 msyslog(LOG_ERR, "crypto_iff %s\n",
2243 ERR_error_string(ERR_get_error(), NULL));
2248 * Compute g^(k + b r) g^(q - b)r mod p.
2250 BN_mod_exp(bn, dsa->pub_key, peer->iffval, dsa->p, bctx);
2251 BN_mod_exp(bk, dsa->g, sdsa->r, dsa->p, bctx);
2252 BN_mod_mul(bn, bn, bk, dsa->p, bctx);
2255 * Verify the hash of the result matches hash(x).
2258 temp = BN_cmp(bn, sdsa->s);
2259 BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
2260 BN_free(peer->iffval);
2261 peer->iffval = NULL;
2271 ***********************************************************************
2273 * The following routines implement the Guillou-Quisquater (GQ) *
2276 ***********************************************************************
2278 * The Guillou-Quisquater (GQ) identity scheme is intended for use when
2279 * the ntp-genkeys program generates the certificates used in the
2280 * protocol and the group key can be conveyed in a certificate extension
2281 * field. The scheme is self contained and independent of new
2282 * generations of host keys, sign keys and certificates.
2284 * The GQ identity scheme is based on RSA cryptography and algorithms
2285 * described in Stinson p. 300 (with errors). The GQ values hide in a
2286 * RSA cuckoo structure, but only the modulus is used. The 512-bit
2287 * public modulus is n = p q, where p and q are secret large primes. The
2288 * TA rolls random group key b disguised as a RSA structure member.
2289 * Except for the public key, these values are shared only among group
2290 * members and never revealed in messages.
2292 * When rolling new certificates, Bob recomputes the private and
2293 * public keys. The private key u is a random roll, while the public key
2294 * is the inverse obscured by the group key v = (u^-1)^b. These values
2295 * replace the private and public keys normally generated by the RSA
2296 * scheme. Alice challenges Bob to confirm identity using the protocol
2301 * The scheme goes like this. Both Alice and Bob have the same modulus n
2302 * and some random b as the group key. These values are computed and
2303 * distributed in advance via secret means, although only the group key
2304 * b is truly secret. Each has a private random private key u and public
2305 * key (u^-1)^b, although not necessarily the same ones. Bob and Alice
2306 * can regenerate the key pair from time to time without affecting
2307 * operations. The public key is conveyed on the certificate in an
2308 * extension field; the private key is never revealed.
2310 * Alice rolls new random challenge r and sends to Bob in the GQ
2311 * request message. Bob rolls new random k, then computes y = k u^r mod
2312 * n and x = k^b mod n and sends (y, hash(x)) to Alice in the response
2313 * message. Besides making the response shorter, the hash makes it
2314 * effectivey impossible for an intruder to solve for b by observing
2315 * a number of these messages.
2317 * Alice receives the response and computes y^b v^r mod n. After a bit
2318 * of algebra, this simplifies to k^b. If the hash of this result
2319 * matches hash(x), Alice knows that Bob has the group key b. The signed
2320 * response binds this knowledge to Bob's private key and the public key
2321 * previously received in his certificate.
2323 * crypto_alice2 - construct Alice's challenge in GQ scheme
2327 * XEVNT_PUB bad or missing public key
2328 * XEVNT_ID bad or missing identity parameters
2332 struct peer *peer, /* peer pointer */
2333 struct value *vp /* value pointer */
2336 RSA *rsa; /* GQ parameters */
2337 BN_CTX *bctx; /* BIGNUM context */
2338 EVP_MD_CTX ctx; /* signature context */
2343 * The identity parameters must have correct format and content.
2345 if (peer->ident_pkey == NULL)
2347 if ((rsa = peer->ident_pkey->pkey.rsa) == NULL) {
2348 msyslog(LOG_INFO, "crypto_alice2: defective key");
2353 * Roll new random r (0 < r < n). The OpenSSL library has a bug
2354 * omitting BN_rand_range, so we have to do it the hard way.
2356 bctx = BN_CTX_new();
2357 len = BN_num_bytes(rsa->n);
2358 if (peer->iffval != NULL)
2359 BN_free(peer->iffval);
2360 peer->iffval = BN_new();
2361 BN_rand(peer->iffval, len * 8, -1, 1); /* r mod n */
2362 BN_mod(peer->iffval, peer->iffval, rsa->n, bctx);
2366 * Sign and send to Bob. The filestamp is from the local file.
2368 tstamp = crypto_time();
2369 memset(vp, 0, sizeof(struct value));
2370 vp->tstamp = htonl(tstamp);
2371 vp->fstamp = htonl(peer->fstamp);
2372 vp->vallen = htonl(len);
2373 vp->ptr = emalloc(len);
2374 BN_bn2bin(peer->iffval, vp->ptr);
2378 vp->sig = emalloc(sign_siglen);
2379 EVP_SignInit(&ctx, sign_digest);
2380 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2381 EVP_SignUpdate(&ctx, vp->ptr, len);
2382 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2383 vp->siglen = htonl(len);
2389 * crypto_bob2 - construct Bob's response to Alice's challenge
2393 * XEVNT_PUB bad or missing public key
2397 struct exten *ep, /* extension pointer */
2398 struct value *vp /* value pointer */
2401 RSA *rsa; /* GQ parameters */
2402 DSA_SIG *sdsa; /* DSA parameters */
2403 BN_CTX *bctx; /* BIGNUM context */
2404 EVP_MD_CTX ctx; /* signature context */
2405 tstamp_t tstamp; /* NTP timestamp */
2406 BIGNUM *r, *k, *g, *y;
2411 * If the GQ parameters are not valid, something awful
2412 * happened or we are being tormented.
2414 if (!(crypto_flags & CRYPTO_FLAG_GQ)) {
2415 msyslog(LOG_INFO, "crypto_bob2: scheme unavailable");
2418 rsa = gqpar_pkey->pkey.rsa;
2421 * Extract r from the challenge.
2423 len = ntohl(ep->vallen);
2424 if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2425 msyslog(LOG_ERR, "crypto_bob2 %s\n",
2426 ERR_error_string(ERR_get_error(), NULL));
2431 * Bob rolls random k (0 < k < n), computes y = k u^r mod n and
2432 * x = k^b mod n, then sends (y, hash(x)) to Alice.
2434 bctx = BN_CTX_new(); k = BN_new(); g = BN_new(); y = BN_new();
2435 sdsa = DSA_SIG_new();
2436 BN_rand(k, len * 8, -1, 1); /* k */
2437 BN_mod(k, k, rsa->n, bctx);
2438 BN_mod_exp(y, rsa->p, r, rsa->n, bctx); /* u^r mod n */
2439 BN_mod_mul(y, k, y, rsa->n, bctx); /* k u^r mod n */
2440 sdsa->r = BN_dup(y);
2441 BN_mod_exp(g, k, rsa->e, rsa->n, bctx); /* k^b mod n */
2443 sdsa->s = BN_dup(g);
2445 BN_free(r); BN_free(k); BN_free(g); BN_free(y);
2448 * Encode the values in ASN.1 and sign.
2450 tstamp = crypto_time();
2451 memset(vp, 0, sizeof(struct value));
2452 vp->tstamp = htonl(tstamp);
2453 vp->fstamp = htonl(gq_fstamp);
2454 len = i2d_DSA_SIG(sdsa, NULL);
2456 msyslog(LOG_ERR, "crypto_bob2 %s\n",
2457 ERR_error_string(ERR_get_error(), NULL));
2461 vp->vallen = htonl(len);
2464 i2d_DSA_SIG(sdsa, &ptr);
2469 vp->sig = emalloc(sign_siglen);
2470 EVP_SignInit(&ctx, sign_digest);
2471 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2472 EVP_SignUpdate(&ctx, vp->ptr, len);
2473 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2474 vp->siglen = htonl(len);
2480 * crypto_gq - verify Bob's response to Alice's challenge
2484 * XEVNT_PUB bad or missing public key
2485 * XEVNT_FSP bad filestamp
2486 * XEVNT_ID bad or missing identity parameters
2490 struct exten *ep, /* extension pointer */
2491 struct peer *peer /* peer structure pointer */
2494 RSA *rsa; /* GQ parameters */
2495 BN_CTX *bctx; /* BIGNUM context */
2496 DSA_SIG *sdsa; /* RSA signature context fake */
2503 * If the GQ parameters are not valid or no challenge was sent,
2504 * something awful happened or we are being tormented.
2506 if (peer->ident_pkey == NULL) {
2507 msyslog(LOG_INFO, "crypto_gq: scheme unavailable");
2510 if (ntohl(ep->fstamp) != peer->fstamp) {
2511 msyslog(LOG_INFO, "crypto_gq: invalid filestamp %u",
2515 if ((rsa = peer->ident_pkey->pkey.rsa) == NULL) {
2516 msyslog(LOG_INFO, "crypto_gq: defective key");
2519 if (peer->iffval == NULL) {
2520 msyslog(LOG_INFO, "crypto_gq: missing challenge");
2525 * Extract the y = k u^r and hash(x = k^b) values from the
2528 bctx = BN_CTX_new(); y = BN_new(); v = BN_new();
2529 len = ntohl(ep->vallen);
2530 ptr = (const u_char *)ep->pkt;
2531 if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2532 msyslog(LOG_ERR, "crypto_gq %s\n",
2533 ERR_error_string(ERR_get_error(), NULL));
2538 * Compute v^r y^b mod n.
2540 BN_mod_exp(v, peer->grpkey, peer->iffval, rsa->n, bctx);
2542 BN_mod_exp(y, sdsa->r, rsa->e, rsa->n, bctx); /* y^b mod n */
2543 BN_mod_mul(y, v, y, rsa->n, bctx); /* v^r y^b mod n */
2546 * Verify the hash of the result matches hash(x).
2549 temp = BN_cmp(y, sdsa->s);
2550 BN_CTX_free(bctx); BN_free(y); BN_free(v);
2551 BN_free(peer->iffval);
2552 peer->iffval = NULL;
2562 ***********************************************************************
2564 * The following routines implement the Mu-Varadharajan (MV) identity *
2567 ***********************************************************************
2570 * The Mu-Varadharajan (MV) cryptosystem was originally intended when
2571 * servers broadcast messages to clients, but clients never send
2572 * messages to servers. There is one encryption key for the server and a
2573 * separate decryption key for each client. It operated something like a
2574 * pay-per-view satellite broadcasting system where the session key is
2575 * encrypted by the broadcaster and the decryption keys are held in a
2576 * tamperproof set-top box.
2578 * The MV parameters and private encryption key hide in a DSA cuckoo
2579 * structure which uses the same parameters, but generated in a
2580 * different way. The values are used in an encryption scheme similar to
2581 * El Gamal cryptography and a polynomial formed from the expansion of
2582 * product terms (x - x[j]), as described in Mu, Y., and V.
2583 * Varadharajan: Robust and Secure Broadcasting, Proc. Indocrypt 2001,
2584 * 223-231. The paper has significant errors and serious omissions.
2586 * Let q be the product of n distinct primes s'[j] (j = 1...n), where
2587 * each s'[j] has m significant bits. Let p be a prime p = 2 * q + 1, so
2588 * that q and each s'[j] divide p - 1 and p has M = n * m + 1
2589 * significant bits. The elements x mod q of Zq with the elements 2 and
2590 * the primes removed form a field Zq* valid for polynomial arithetic.
2591 * Let g be a generator of Zp; that is, gcd(g, p - 1) = 1 and g^q = 1
2592 * mod p. We expect M to be in the 500-bit range and n relatively small,
2593 * like 25, so the likelihood of a randomly generated element of x mod q
2594 * of Zq colliding with a factor of p - 1 is very small and can be
2595 * avoided. Associated with each s'[j] is an element s[j] such that s[j]
2596 * s'[j] = s'[j] mod q. We find s[j] as the quotient (q + s'[j]) /
2597 * s'[j]. These are the parameters of the scheme and they are expensive
2600 * We set up an instance of the scheme as follows. A set of random
2601 * values x[j] mod q (j = 1...n), are generated as the zeros of a
2602 * polynomial of order n. The product terms (x - x[j]) are expanded to
2603 * form coefficients a[i] mod q (i = 0...n) in powers of x. These are
2604 * used as exponents of the generator g mod p to generate the private
2605 * encryption key A. The pair (gbar, ghat) of public server keys and the
2606 * pairs (xbar[j], xhat[j]) (j = 1...n) of private client keys are used
2607 * to construct the decryption keys. The devil is in the details.
2609 * The distinguishing characteristic of this scheme is the capability to
2610 * revoke keys. Included in the calculation of E, gbar and ghat is the
2611 * product s = prod(s'[j]) (j = 1...n) above. If the factor s'[j] is
2612 * subsequently removed from the product and E, gbar and ghat
2613 * recomputed, the jth client will no longer be able to compute E^-1 and
2614 * thus unable to decrypt the block.
2618 * The scheme goes like this. Bob has the server values (p, A, q, gbar,
2619 * ghat) and Alice the client values (p, xbar, xhat).
2621 * Alice rolls new random challenge r (0 < r < p) and sends to Bob in
2622 * the MV request message. Bob rolls new random k (0 < k < q), encrypts
2623 * y = A^k mod p (a permutation) and sends (hash(y), gbar^k, ghat^k) to
2626 * Alice receives the response and computes the decryption key (the
2627 * inverse permutation) from previously obtained (xbar, xhat) and
2628 * (gbar^k, ghat^k) in the message. She computes the inverse, which is
2629 * unique by reasons explained in the ntp-keygen.c program sources. If
2630 * the hash of this result matches hash(y), Alice knows that Bob has the
2631 * group key b. The signed response binds this knowledge to Bob's
2632 * private key and the public key previously received in his
2635 * crypto_alice3 - construct Alice's challenge in MV scheme
2639 * XEVNT_PUB bad or missing public key
2640 * XEVNT_ID bad or missing identity parameters
2644 struct peer *peer, /* peer pointer */
2645 struct value *vp /* value pointer */
2648 DSA *dsa; /* MV parameters */
2649 BN_CTX *bctx; /* BIGNUM context */
2650 EVP_MD_CTX ctx; /* signature context */
2655 * The identity parameters must have correct format and content.
2657 if (peer->ident_pkey == NULL)
2659 if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
2660 msyslog(LOG_INFO, "crypto_alice3: defective key");
2665 * Roll new random r (0 < r < q). The OpenSSL library has a bug
2666 * omitting BN_rand_range, so we have to do it the hard way.
2668 bctx = BN_CTX_new();
2669 len = BN_num_bytes(dsa->p);
2670 if (peer->iffval != NULL)
2671 BN_free(peer->iffval);
2672 peer->iffval = BN_new();
2673 BN_rand(peer->iffval, len * 8, -1, 1); /* r */
2674 BN_mod(peer->iffval, peer->iffval, dsa->p, bctx);
2678 * Sign and send to Bob. The filestamp is from the local file.
2680 tstamp = crypto_time();
2681 memset(vp, 0, sizeof(struct value));
2682 vp->tstamp = htonl(tstamp);
2683 vp->fstamp = htonl(peer->fstamp);
2684 vp->vallen = htonl(len);
2685 vp->ptr = emalloc(len);
2686 BN_bn2bin(peer->iffval, vp->ptr);
2690 vp->sig = emalloc(sign_siglen);
2691 EVP_SignInit(&ctx, sign_digest);
2692 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2693 EVP_SignUpdate(&ctx, vp->ptr, len);
2694 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2695 vp->siglen = htonl(len);
2701 * crypto_bob3 - construct Bob's response to Alice's challenge
2705 * XEVNT_PUB bad or missing public key
2709 struct exten *ep, /* extension pointer */
2710 struct value *vp /* value pointer */
2713 DSA *dsa; /* MV parameters */
2714 DSA *sdsa; /* DSA signature context fake */
2715 BN_CTX *bctx; /* BIGNUM context */
2716 EVP_MD_CTX ctx; /* signature context */
2717 tstamp_t tstamp; /* NTP timestamp */
2723 * If the MV parameters are not valid, something awful
2724 * happened or we are being tormented.
2726 if (!(crypto_flags & CRYPTO_FLAG_MV)) {
2727 msyslog(LOG_INFO, "crypto_bob3: scheme unavailable");
2730 dsa = mvpar_pkey->pkey.dsa;
2733 * Extract r from the challenge.
2735 len = ntohl(ep->vallen);
2736 if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2737 msyslog(LOG_ERR, "crypto_bob3 %s\n",
2738 ERR_error_string(ERR_get_error(), NULL));
2743 * Bob rolls random k (0 < k < q), making sure it is not a
2744 * factor of q. He then computes y = A^k r and sends (hash(y),
2745 * gbar^k, ghat^k) to Alice.
2747 bctx = BN_CTX_new(); k = BN_new(); u = BN_new();
2749 sdsa->p = BN_new(); sdsa->q = BN_new(); sdsa->g = BN_new();
2751 BN_rand(k, BN_num_bits(dsa->q), 0, 0);
2752 BN_mod(k, k, dsa->q, bctx);
2753 BN_gcd(u, k, dsa->q, bctx);
2757 BN_mod_exp(u, dsa->g, k, dsa->p, bctx); /* A r */
2758 BN_mod_mul(u, u, r, dsa->p, bctx);
2759 bighash(u, sdsa->p);
2760 BN_mod_exp(sdsa->q, dsa->priv_key, k, dsa->p, bctx); /* gbar */
2761 BN_mod_exp(sdsa->g, dsa->pub_key, k, dsa->p, bctx); /* ghat */
2762 BN_CTX_free(bctx); BN_free(k); BN_free(r); BN_free(u);
2765 * Encode the values in ASN.1 and sign.
2767 tstamp = crypto_time();
2768 memset(vp, 0, sizeof(struct value));
2769 vp->tstamp = htonl(tstamp);
2770 vp->fstamp = htonl(mv_fstamp);
2771 len = i2d_DSAparams(sdsa, NULL);
2773 msyslog(LOG_ERR, "crypto_bob3 %s\n",
2774 ERR_error_string(ERR_get_error(), NULL));
2778 vp->vallen = htonl(len);
2781 i2d_DSAparams(sdsa, &ptr);
2786 vp->sig = emalloc(sign_siglen);
2787 EVP_SignInit(&ctx, sign_digest);
2788 EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2789 EVP_SignUpdate(&ctx, vp->ptr, len);
2790 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2791 vp->siglen = htonl(len);
2797 * crypto_mv - verify Bob's response to Alice's challenge
2801 * XEVNT_PUB bad or missing public key
2802 * XEVNT_FSP bad filestamp
2803 * XEVNT_ID bad or missing identity parameters
2807 struct exten *ep, /* extension pointer */
2808 struct peer *peer /* peer structure pointer */
2811 DSA *dsa; /* MV parameters */
2812 DSA *sdsa; /* DSA parameters */
2813 BN_CTX *bctx; /* BIGNUM context */
2820 * If the MV parameters are not valid or no challenge was sent,
2821 * something awful happened or we are being tormented.
2823 if (peer->ident_pkey == NULL) {
2824 msyslog(LOG_INFO, "crypto_mv: scheme unavailable");
2827 if (ntohl(ep->fstamp) != peer->fstamp) {
2828 msyslog(LOG_INFO, "crypto_mv: invalid filestamp %u",
2832 if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
2833 msyslog(LOG_INFO, "crypto_mv: defective key");
2836 if (peer->iffval == NULL) {
2837 msyslog(LOG_INFO, "crypto_mv: missing challenge");
2842 * Extract the (hash(y), gbar, ghat) values from the response.
2844 bctx = BN_CTX_new(); k = BN_new(); u = BN_new(); v = BN_new();
2845 len = ntohl(ep->vallen);
2846 ptr = (const u_char *)ep->pkt;
2847 if ((sdsa = d2i_DSAparams(NULL, &ptr, len)) == NULL) {
2848 msyslog(LOG_ERR, "crypto_mv %s\n",
2849 ERR_error_string(ERR_get_error(), NULL));
2854 * Compute (gbar^xhat ghat^xbar)^-1 mod p.
2856 BN_mod_exp(u, sdsa->q, dsa->pub_key, dsa->p, bctx);
2857 BN_mod_exp(v, sdsa->g, dsa->priv_key, dsa->p, bctx);
2858 BN_mod_mul(u, u, v, dsa->p, bctx);
2859 BN_mod_inverse(u, u, dsa->p, bctx);
2860 BN_mod_mul(v, u, peer->iffval, dsa->p, bctx);
2863 * The result should match the hash of r mod p.
2866 temp = BN_cmp(v, sdsa->p);
2867 BN_CTX_free(bctx); BN_free(k); BN_free(u); BN_free(v);
2868 BN_free(peer->iffval);
2869 peer->iffval = NULL;
2879 ***********************************************************************
2881 * The following routines are used to manipulate certificates *
2883 ***********************************************************************
2886 * cert_parse - parse x509 certificate and create info/value structures.
2888 * The server certificate includes the version number, issuer name,
2889 * subject name, public key and valid date interval. If the issuer name
2890 * is the same as the subject name, the certificate is self signed and
2891 * valid only if the server is configured as trustable. If the names are
2892 * different, another issuer has signed the server certificate and
2893 * vouched for it. In this case the server certificate is valid if
2894 * verified by the issuer public key.
2896 * Returns certificate info/value pointer if valid, NULL if not.
2898 struct cert_info * /* certificate information structure */
2900 u_char *asn1cert, /* X509 certificate */
2901 u_int len, /* certificate length */
2902 tstamp_t fstamp /* filestamp */
2905 X509 *cert; /* X509 certificate */
2906 X509_EXTENSION *ext; /* X509v3 extension */
2907 struct cert_info *ret; /* certificate info/value */
2909 X509V3_EXT_METHOD *method;
2910 char pathbuf[MAXFILENAME];
2916 * Decode ASN.1 objects and construct certificate structure.
2919 if ((cert = d2i_X509(NULL, &uptr, len)) == NULL) {
2920 msyslog(LOG_ERR, "cert_parse %s\n",
2921 ERR_error_string(ERR_get_error(), NULL));
2926 * Extract version, subject name and public key.
2928 ret = emalloc(sizeof(struct cert_info));
2929 memset(ret, 0, sizeof(struct cert_info));
2930 if ((ret->pkey = X509_get_pubkey(cert)) == NULL) {
2931 msyslog(LOG_ERR, "cert_parse %s\n",
2932 ERR_error_string(ERR_get_error(), NULL));
2937 ret->version = X509_get_version(cert);
2938 X509_NAME_oneline(X509_get_subject_name(cert), pathbuf,
2940 ptr = strstr(pathbuf, "CN=");
2942 msyslog(LOG_INFO, "cert_parse: invalid subject %s",
2948 ret->subject = emalloc(strlen(ptr) + 1);
2949 strcpy(ret->subject, ptr + 3);
2952 * Extract remaining objects. Note that the NTP serial number is
2953 * the NTP seconds at the time of signing, but this might not be
2954 * the case for other authority. We don't bother to check the
2955 * objects at this time, since the real crunch can happen only
2956 * when the time is valid but not yet certificated.
2958 ret->nid = OBJ_obj2nid(cert->cert_info->signature->algorithm);
2959 ret->digest = (const EVP_MD *)EVP_get_digestbynid(ret->nid);
2961 (u_long)ASN1_INTEGER_get(X509_get_serialNumber(cert));
2962 X509_NAME_oneline(X509_get_issuer_name(cert), pathbuf,
2964 if ((ptr = strstr(pathbuf, "CN=")) == NULL) {
2965 msyslog(LOG_INFO, "cert_parse: invalid issuer %s",
2971 ret->issuer = emalloc(strlen(ptr) + 1);
2972 strcpy(ret->issuer, ptr + 3);
2973 ret->first = asn2ntp(X509_get_notBefore(cert));
2974 ret->last = asn2ntp(X509_get_notAfter(cert));
2977 * Extract extension fields. These are ad hoc ripoffs of
2978 * currently assigned functions and will certainly be changed
2979 * before prime time.
2981 cnt = X509_get_ext_count(cert);
2982 for (i = 0; i < cnt; i++) {
2983 ext = X509_get_ext(cert, i);
2984 method = X509V3_EXT_get(ext);
2985 temp = OBJ_obj2nid(ext->object);
2989 * If a key_usage field is present, we decode whether
2990 * this is a trusted or private certificate. This is
2991 * dorky; all we want is to compare NIDs, but OpenSSL
2992 * insists on BIO text strings.
2994 case NID_ext_key_usage:
2995 bp = BIO_new(BIO_s_mem());
2996 X509V3_EXT_print(bp, ext, 0, 0);
2997 BIO_gets(bp, pathbuf, MAXFILENAME);
3001 printf("cert_parse: %s: %s\n",
3002 OBJ_nid2ln(temp), pathbuf);
3004 if (strcmp(pathbuf, "Trust Root") == 0)
3005 ret->flags |= CERT_TRUST;
3006 else if (strcmp(pathbuf, "Private") == 0)
3007 ret->flags |= CERT_PRIV;
3011 * If a NID_subject_key_identifier field is present, it
3012 * contains the GQ public key.
3014 case NID_subject_key_identifier:
3015 ret->grplen = ext->value->length - 2;
3016 ret->grpkey = emalloc(ret->grplen);
3017 memcpy(ret->grpkey, &ext->value->data[2],
3024 * If certificate is self signed, verify signature.
3026 if (strcmp(ret->subject, ret->issuer) == 0) {
3027 if (!X509_verify(cert, ret->pkey)) {
3029 "cert_parse: invalid signature not verified %s",
3038 * Verify certificate valid times. Note that certificates cannot
3041 if (ret->first > ret->last || ret->first < fstamp) {
3043 "cert_parse: expired %s",
3051 * Build the value structure to sign and send later.
3053 ret->cert.fstamp = htonl(fstamp);
3054 ret->cert.vallen = htonl(len);
3055 ret->cert.ptr = emalloc(len);
3056 memcpy(ret->cert.ptr, asn1cert, len);
3059 X509_print_fp(stdout, cert);
3067 * cert_sign - sign x509 certificate and update value structure.
3069 * The certificate request is a copy of the client certificate, which
3070 * includes the version number, subject name and public key of the
3071 * client. The resulting certificate includes these values plus the
3072 * serial number, issuer name and validity interval of the server. The
3073 * validity interval extends from the current time to the same time one
3074 * year hence. For NTP purposes, it is convenient to use the NTP seconds
3075 * of the current time as the serial number.
3079 * XEVNT_PUB bad or missing public key
3080 * XEVNT_CRT bad or missing certificate
3081 * XEVNT_VFY certificate not verified
3085 struct exten *ep, /* extension field pointer */
3086 struct value *vp /* value pointer */
3089 X509 *req; /* X509 certificate request */
3090 X509 *cert; /* X509 certificate */
3091 X509_EXTENSION *ext; /* certificate extension */
3092 ASN1_INTEGER *serial; /* serial number */
3093 X509_NAME *subj; /* distinguished (common) name */
3094 EVP_PKEY *pkey; /* public key */
3095 EVP_MD_CTX ctx; /* message digest context */
3096 tstamp_t tstamp; /* NTP timestamp */
3102 * Decode ASN.1 objects and construct certificate structure.
3104 tstamp = crypto_time();
3108 ptr = (u_char *)ep->pkt;
3109 if ((req = d2i_X509(NULL, &ptr, ntohl(ep->vallen))) == NULL) {
3110 msyslog(LOG_ERR, "cert_sign %s\n",
3111 ERR_error_string(ERR_get_error(), NULL));
3115 * Extract public key and check for errors.
3117 if ((pkey = X509_get_pubkey(req)) == NULL) {
3118 msyslog(LOG_ERR, "cert_sign %s\n",
3119 ERR_error_string(ERR_get_error(), NULL));
3125 * Generate X509 certificate signed by this server. For this
3126 * prupose the issuer name is the server name. Also copy any
3127 * extensions that might be present.
3130 X509_set_version(cert, X509_get_version(req));
3131 serial = ASN1_INTEGER_new();
3132 ASN1_INTEGER_set(serial, tstamp);
3133 X509_set_serialNumber(cert, serial);
3134 X509_gmtime_adj(X509_get_notBefore(cert), 0L);
3135 X509_gmtime_adj(X509_get_notAfter(cert), YEAR);
3136 subj = X509_get_issuer_name(cert);
3137 X509_NAME_add_entry_by_txt(subj, "commonName", MBSTRING_ASC,
3138 (unsigned char *) sys_hostname, strlen(sys_hostname), -1, 0);
3139 subj = X509_get_subject_name(req);
3140 X509_set_subject_name(cert, subj);
3141 X509_set_pubkey(cert, pkey);
3142 ext = X509_get_ext(req, 0);
3143 temp = X509_get_ext_count(req);
3144 for (i = 0; i < temp; i++) {
3145 ext = X509_get_ext(req, i);
3146 X509_add_ext(cert, ext, -1);
3151 * Sign and verify the certificate.
3153 X509_sign(cert, sign_pkey, sign_digest);
3154 if (!X509_verify(cert, sign_pkey)) {
3155 printf("cert_sign\n%s\n",
3156 ERR_error_string(ERR_get_error(), NULL));
3160 len = i2d_X509(cert, NULL);
3163 * Build and sign the value structure. We have to sign it here,
3164 * since the response has to be returned right away. This is a
3167 memset(vp, 0, sizeof(struct value));
3168 vp->tstamp = htonl(tstamp);
3169 vp->fstamp = ep->fstamp;
3170 vp->vallen = htonl(len);
3171 vp->ptr = emalloc(len);
3173 i2d_X509(cert, &ptr);
3175 vp->sig = emalloc(sign_siglen);
3176 EVP_SignInit(&ctx, sign_digest);
3177 EVP_SignUpdate(&ctx, (u_char *)vp, 12);
3178 EVP_SignUpdate(&ctx, vp->ptr, len);
3179 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
3180 vp->siglen = htonl(len);
3183 X509_print_fp(stdout, cert);
3191 * cert_valid - verify certificate with given public key
3193 * This is pretty ugly, as the certificate has to be verified in the
3194 * OpenSSL X509 structure, not in the DER format in the info/value
3199 * XEVNT_VFY certificate not verified
3203 struct cert_info *cinf, /* certificate information structure */
3204 EVP_PKEY *pkey /* public key */
3207 X509 *cert; /* X509 certificate */
3210 if (cinf->flags & CERT_SIGN)
3212 ptr = (u_char *)cinf->cert.ptr;
3213 cert = d2i_X509(NULL, &ptr, ntohl(cinf->cert.vallen));
3214 if (!X509_verify(cert, pkey))
3216 cinf->flags |= CERT_SIGN;
3223 * cert - install certificate in certificate list
3225 * This routine encodes an extension field into a certificate info/value
3226 * structure. It searches the certificate list for duplicates and
3227 * expunges whichever is older. It then searches the list for other
3228 * certificates that might be verified by this latest one. Finally, it
3229 * inserts this certificate first on the list.
3233 * XEVNT_PER certificate expired
3234 * XEVNT_CRT bad or missing certificate
3238 struct exten *ep, /* cert info/value */
3239 struct peer *peer /* peer structure */
3242 struct cert_info *cp, *xp, *yp, **zp;
3247 * Parse and validate the signed certificate. If valid,
3248 * construct the info/value structure; otherwise, scamper home.
3249 * Note this allows a certificate not-before time to be in the
3250 * future, but not a not-after time to be in the past.
3252 if ((cp = cert_parse((u_char *)ep->pkt, ntohl(ep->vallen),
3253 ntohl(ep->fstamp))) == NULL)
3256 tstamp = crypto_time();
3257 if (tstamp > cp->last) {
3263 * Scan certificate list looking for another certificate with
3264 * the same subject and issuer. If another is found with the
3265 * same or older filestamp, unlink it and return the goodies to
3266 * the heap. If another is found with a later filetsamp, discard
3267 * the new one and leave the building.
3272 for (xp = cinfo; xp != NULL; xp = xp->link) {
3273 if (strcmp(cp->subject, xp->subject) == 0 &&
3274 strcmp(cp->issuer, xp->issuer) == 0) {
3275 if (ntohl(cp->cert.fstamp) <=
3276 ntohl(xp->cert.fstamp)) {
3291 * Scan the certificate list to see if Y is signed by X.
3293 for (yp = cinfo; yp != NULL; yp = yp->link) {
3294 for (xp = cinfo; xp != NULL; xp = xp->link) {
3295 if (yp->flags & CERT_ERROR)
3299 * If issuer Y matches subject X and signature Y
3300 * is valid using public key X, then Y is valid.
3302 if (strcmp(yp->issuer, xp->subject) != 0)
3305 if (cert_valid(yp, xp->pkey) != XEVNT_OK) {
3306 yp->flags |= CERT_ERROR;
3309 xp->flags |= CERT_SIGN;
3312 * If X is trusted, then Y is trusted. Note that
3313 * we might stumble over a self signed
3314 * certificate that is not trusted, at least
3315 * temporarily. This can happen when a dude
3316 * first comes up, but has not synchronized the
3317 * clock and had its certificate signed by its
3318 * server. In case of broken certificate trail,
3319 * this might result in a loop that could
3320 * persist until timeout.
3322 if (!(xp->flags & CERT_TRUST))
3325 yp->flags |= CERT_TRUST;
3328 * If subject Y matches the server subject name,
3329 * then Y has completed the certificate trail.
3330 * Save the group key and light the valid bit.
3332 if (strcmp(yp->subject, peer->subject) != 0)
3335 if (yp->grpkey != NULL) {
3336 if (peer->grpkey != NULL)
3337 BN_free(peer->grpkey);
3338 peer->grpkey = BN_bin2bn(yp->grpkey,
3341 peer->crypto |= CRYPTO_FLAG_VALID;
3344 * If the server has an an identity scheme,
3345 * fetch the identity credentials. If not, the
3346 * identity is verified only by the trusted
3347 * certificate. The next signature will set the
3350 if (peer->crypto & (CRYPTO_FLAG_GQ |
3351 CRYPTO_FLAG_IFF | CRYPTO_FLAG_MV))
3354 peer->crypto |= CRYPTO_FLAG_VRFY;
3359 * That was awesome. Now update the timestamps and signatures.
3367 * cert_free - free certificate information structure
3371 struct cert_info *cinf /* certificate info/value structure */
3374 if (cinf->pkey != NULL)
3375 EVP_PKEY_free(cinf->pkey);
3376 if (cinf->subject != NULL)
3377 free(cinf->subject);
3378 if (cinf->issuer != NULL)
3380 if (cinf->grpkey != NULL)
3382 value_free(&cinf->cert);
3388 ***********************************************************************
3390 * The following routines are used only at initialization time *
3392 ***********************************************************************
3395 * crypto_key - load cryptographic parameters and keys from files
3397 * This routine loads a PEM-encoded public/private key pair and extracts
3398 * the filestamp from the file name.
3400 * Returns public key pointer if valid, NULL if not. Side effect updates
3401 * the filestamp if valid.
3405 char *cp, /* file name */
3406 tstamp_t *fstamp /* filestamp */
3409 FILE *str; /* file handle */
3410 EVP_PKEY *pkey = NULL; /* public/private key */
3411 char filename[MAXFILENAME]; /* name of key file */
3412 char linkname[MAXFILENAME]; /* filestamp buffer) */
3413 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3417 * Open the key file. If the first character of the file name is
3418 * not '/', prepend the keys directory string. If something goes
3419 * wrong, abandon ship.
3422 strcpy(filename, cp);
3424 snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
3425 str = fopen(filename, "r");
3430 * Read the filestamp, which is contained in the first line.
3432 if ((ptr = fgets(linkname, MAXFILENAME, str)) == NULL) {
3433 msyslog(LOG_ERR, "crypto_key: no data %s\n",
3437 if ((ptr = strrchr(ptr, '.')) == NULL) {
3438 msyslog(LOG_ERR, "crypto_key: no filestamp %s\n",
3442 if (sscanf(++ptr, "%u", fstamp) != 1) {
3443 msyslog(LOG_ERR, "crypto_key: invalid timestamp %s\n",
3449 * Read and decrypt PEM-encoded private key.
3451 pkey = PEM_read_PrivateKey(str, NULL, NULL, passwd);
3454 msyslog(LOG_ERR, "crypto_key %s\n",
3455 ERR_error_string(ERR_get_error(), NULL));
3460 * Leave tracks in the cryptostats.
3462 if ((ptr = strrchr(linkname, '\n')) != NULL)
3464 sprintf(statstr, "%s mod %d", &linkname[2],
3465 EVP_PKEY_size(pkey) * 8);
3466 record_crypto_stats(NULL, statstr);
3469 printf("crypto_key: %s\n", statstr);
3471 if (EVP_MD_type(pkey) == EVP_PKEY_DSA)
3472 DSA_print_fp(stdout, pkey->pkey.dsa, 0);
3474 RSA_print_fp(stdout, pkey->pkey.rsa, 0);
3482 * crypto_cert - load certificate from file
3484 * This routine loads a X.509 RSA or DSA certificate from a file and
3485 * constructs a info/cert value structure for this machine. The
3486 * structure includes a filestamp extracted from the file name. Later
3487 * the certificate can be sent to another machine by request.
3489 * Returns certificate info/value pointer if valid, NULL if not.
3491 static struct cert_info * /* certificate information */
3493 char *cp /* file name */
3496 struct cert_info *ret; /* certificate information */
3497 FILE *str; /* file handle */
3498 char filename[MAXFILENAME]; /* name of certificate file */
3499 char linkname[MAXFILENAME]; /* filestamp buffer */
3500 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3501 tstamp_t fstamp; /* filestamp */
3504 char *name, *header;
3508 * Open the certificate file. If the first character of the file
3509 * name is not '/', prepend the keys directory string. If
3510 * something goes wrong, abandon ship.
3513 strcpy(filename, cp);
3515 snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
3516 str = fopen(filename, "r");
3521 * Read the filestamp, which is contained in the first line.
3523 if ((ptr = fgets(linkname, MAXFILENAME, str)) == NULL) {
3524 msyslog(LOG_ERR, "crypto_cert: no data %s\n",
3528 if ((ptr = strrchr(ptr, '.')) == NULL) {
3529 msyslog(LOG_ERR, "crypto_cert: no filestamp %s\n",
3533 if (sscanf(++ptr, "%u", &fstamp) != 1) {
3534 msyslog(LOG_ERR, "crypto_cert: invalid filestamp %s\n",
3540 * Read PEM-encoded certificate and install.
3542 if (!PEM_read(str, &name, &header, &data, &len)) {
3543 msyslog(LOG_ERR, "crypto_cert %s\n",
3544 ERR_error_string(ERR_get_error(), NULL));
3548 if (strcmp(name, "CERTIFICATE") !=0) {
3549 msyslog(LOG_INFO, "crypto_cert: wrong PEM type %s",
3558 * Parse certificate and generate info/value structure.
3560 ret = cert_parse(data, len, fstamp);
3564 if ((ptr = strrchr(linkname, '\n')) != NULL)
3566 sprintf(statstr, "%s 0x%x len %lu", &linkname[2], ret->flags,
3568 record_crypto_stats(NULL, statstr);
3571 printf("crypto_cert: %s\n", statstr);
3578 * crypto_tai - load leapseconds table from file
3580 * This routine loads the ERTS leapsecond file in NIST text format,
3581 * converts to a value structure and extracts a filestamp from the file
3582 * name. The data are used to establish the TAI offset from UTC, which
3583 * is provided to the kernel if supported. Later the data can be sent to
3584 * another machine on request.
3588 char *cp /* file name */
3591 FILE *str; /* file handle */
3592 char buf[NTP_MAXSTRLEN]; /* file line buffer */
3593 u_int leapsec[MAX_LEAP]; /* NTP time at leaps */
3594 u_int offset; /* offset at leap (s) */
3595 char filename[MAXFILENAME]; /* name of leapseconds file */
3596 char linkname[MAXFILENAME]; /* file link (for filestamp) */
3597 char statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3598 tstamp_t fstamp; /* filestamp */
3604 struct timex ntv; /* kernel interface structure */
3605 #endif /* NTP_API */
3606 #endif /* KERNEL_PLL */
3609 * Open the file and discard comment lines. If the first
3610 * character of the file name is not '/', prepend the keys
3611 * directory string. If the file is not found, not to worry; it
3612 * can be retrieved over the net. But, if it is found with
3613 * errors, we crash and burn.
3616 strcpy(filename, cp);
3618 snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
3619 if ((str = fopen(filename, "r")) == NULL)
3623 * Extract filestamp if present.
3625 rval = readlink(filename, linkname, MAXFILENAME - 1);
3627 linkname[rval] = '\0';
3628 ptr = strrchr(linkname, '.');
3630 ptr = strrchr(filename, '.');
3633 sscanf(++ptr, "%u", &fstamp);
3636 tai_leap.fstamp = htonl(fstamp);
3639 * We are rather paranoid here, since an intruder might cause a
3640 * coredump by infiltrating naughty values. Empty lines and
3641 * comments are ignored. Other lines must begin with two
3642 * integers followed by junk or comments. The first integer is
3643 * the NTP seconds of leap insertion, the second is the offset
3644 * of TAI relative to UTC after that insertion. The second word
3645 * must equal the initial insertion of ten seconds on 1 January
3646 * 1972 plus one second for each succeeding insertion.
3649 while (i < MAX_LEAP) {
3650 ptr = fgets(buf, NTP_MAXSTRLEN - 1, str);
3653 if (strlen(buf) < 1)
3657 if (sscanf(buf, "%u %u", &leapsec[i], &offset) != 2)
3659 if (i != (int)(offset - TAI_1972)) {
3667 "crypto_tai: leapseconds file %s error %d", cp,
3673 * The extension field table entries consists of the NTP seconds
3674 * of leap insertion in reverse order, so that the most recent
3675 * insertion is the first entry in the table.
3678 tai_leap.vallen = htonl(len);
3680 tai_leap.ptr = (unsigned char *) ptr;
3681 for (; i >= 0; i--) {
3682 *ptr++ = (char) htonl(leapsec[i]);
3684 crypto_flags |= CRYPTO_FLAG_TAI;
3685 sys_tai = len / 4 + TAI_1972 - 1;
3688 ntv.modes = MOD_TAI;
3689 ntv.constant = sys_tai;
3690 if (ntp_adjtime(&ntv) == TIME_ERROR)
3692 "crypto_tai: kernel TAI update failed");
3693 #endif /* NTP_API */
3694 #endif /* KERNEL_PLL */
3695 sprintf(statstr, "%s link %d fs %u offset %u", cp, rval, fstamp,
3696 ntohl(tai_leap.vallen) / 4 + TAI_1972 - 1);
3697 record_crypto_stats(NULL, statstr);
3700 printf("crypto_tai: %s\n", statstr);
3706 * crypto_setup - load keys, certificate and leapseconds table
3708 * This routine loads the public/private host key and certificate. If
3709 * available, it loads the public/private sign key, which defaults to
3710 * the host key, and leapseconds table. The host key must be RSA, but
3711 * the sign key can be either RSA or DSA. In either case, the public key
3712 * on the certificate must agree with the sign key.
3717 EVP_PKEY *pkey; /* private/public key pair */
3718 char filename[MAXFILENAME]; /* file name buffer */
3719 l_fp seed; /* crypto PRNG seed as NTP timestamp */
3720 tstamp_t fstamp; /* filestamp */
3721 tstamp_t sstamp; /* sign filestamp */
3726 * Initialize structures.
3730 gethostname(filename, MAXFILENAME);
3731 bytes = strlen(filename) + 1;
3732 sys_hostname = emalloc(bytes);
3733 memcpy(sys_hostname, filename, bytes);
3735 passwd = sys_hostname;
3736 memset(&hostval, 0, sizeof(hostval));
3737 memset(&pubkey, 0, sizeof(pubkey));
3738 memset(&tai_leap, 0, sizeof(tai_leap));
3741 * Load required random seed file and seed the random number
3742 * generator. Be default, it is found in the user home
3743 * directory. The root home directory may be / or /root,
3744 * depending on the system. Wiggle the contents a bit and write
3745 * it back so the sequence does not repeat when we next restart.
3747 ERR_load_crypto_strings();
3748 if (rand_file == NULL) {
3749 if ((RAND_file_name(filename, MAXFILENAME)) != NULL) {
3750 rand_file = emalloc(strlen(filename) + 1);
3751 strcpy(rand_file, filename);
3753 } else if (*rand_file != '/') {
3754 snprintf(filename, MAXFILENAME, "%s/%s", keysdir,
3757 rand_file = emalloc(strlen(filename) + 1);
3758 strcpy(rand_file, filename);
3760 if (rand_file == NULL) {
3762 "crypto_setup: random seed file not specified");
3765 if ((bytes = RAND_load_file(rand_file, -1)) == 0) {
3767 "crypto_setup: random seed file %s not found\n",
3772 RAND_seed(&seed, sizeof(l_fp));
3773 RAND_write_file(rand_file);
3774 OpenSSL_add_all_algorithms();
3778 "crypto_setup: OpenSSL version %lx random seed file %s bytes read %d\n",
3779 SSLeay(), rand_file, bytes);
3783 * Load required host key from file "ntpkey_host_<hostname>". It
3784 * also becomes the default sign key.
3786 if (host_file == NULL) {
3787 snprintf(filename, MAXFILENAME, "ntpkey_host_%s",
3789 host_file = emalloc(strlen(filename) + 1);
3790 strcpy(host_file, filename);
3792 pkey = crypto_key(host_file, &fstamp);
3795 "crypto_setup: host key file %s not found or corrupt",
3802 hostval.fstamp = htonl(fstamp);
3803 if (EVP_MD_type(host_pkey) != EVP_PKEY_RSA) {
3805 "crypto_setup: host key is not RSA key type");
3808 hostval.vallen = htonl(strlen(sys_hostname));
3809 hostval.ptr = (unsigned char *) sys_hostname;
3812 * Construct public key extension field for agreement scheme.
3814 len = i2d_PublicKey(host_pkey, NULL);
3817 i2d_PublicKey(host_pkey, &ptr);
3818 pubkey.vallen = htonl(len);
3819 pubkey.fstamp = hostval.fstamp;
3822 * Load optional sign key from file "ntpkey_sign_<hostname>". If
3823 * loaded, it becomes the sign key.
3825 if (sign_file == NULL) {
3826 snprintf(filename, MAXFILENAME, "ntpkey_sign_%s",
3828 sign_file = emalloc(strlen(filename) + 1);
3829 strcpy(sign_file, filename);
3831 pkey = crypto_key(sign_file, &fstamp);
3836 sign_siglen = EVP_PKEY_size(sign_pkey);
3839 * Load optional IFF parameters from file
3840 * "ntpkey_iff_<hostname>".
3842 if (iffpar_file == NULL) {
3843 snprintf(filename, MAXFILENAME, "ntpkey_iff_%s",
3845 iffpar_file = emalloc(strlen(filename) + 1);
3846 strcpy(iffpar_file, filename);
3848 iffpar_pkey = crypto_key(iffpar_file, &if_fstamp);
3849 if (iffpar_pkey != NULL)
3850 crypto_flags |= CRYPTO_FLAG_IFF;
3853 * Load optional GQ parameters from file "ntpkey_gq_<hostname>".
3855 if (gqpar_file == NULL) {
3856 snprintf(filename, MAXFILENAME, "ntpkey_gq_%s",
3858 gqpar_file = emalloc(strlen(filename) + 1);
3859 strcpy(gqpar_file, filename);
3861 gqpar_pkey = crypto_key(gqpar_file, &gq_fstamp);
3862 if (gqpar_pkey != NULL)
3863 crypto_flags |= CRYPTO_FLAG_GQ;
3866 * Load optional MV parameters from file "ntpkey_mv_<hostname>".
3868 if (mvpar_file == NULL) {
3869 snprintf(filename, MAXFILENAME, "ntpkey_mv_%s",
3871 mvpar_file = emalloc(strlen(filename) + 1);
3872 strcpy(mvpar_file, filename);
3874 mvpar_pkey = crypto_key(mvpar_file, &mv_fstamp);
3875 if (mvpar_pkey != NULL)
3876 crypto_flags |= CRYPTO_FLAG_MV;
3879 * Load required certificate from file "ntpkey_cert_<hostname>".
3881 if (cert_file == NULL) {
3882 snprintf(filename, MAXFILENAME, "ntpkey_cert_%s",
3884 cert_file = emalloc(strlen(filename) + 1);
3885 strcpy(cert_file, filename);
3887 if ((cinfo = crypto_cert(cert_file)) == NULL) {
3889 "certificate file %s not found or corrupt",
3895 * The subject name must be the same as the host name, unless
3896 * the certificate is private, in which case it may have come
3897 * from another host.
3899 if (!(cinfo->flags & CERT_PRIV) && strcmp(cinfo->subject,
3900 sys_hostname) != 0) {
3902 "crypto_setup: certificate %s not for this host",
3909 * It the certificate is trusted, the subject must be the same
3910 * as the issuer, in other words it must be self signed.
3912 if (cinfo->flags & CERT_PRIV && strcmp(cinfo->subject,
3913 cinfo->issuer) != 0) {
3914 if (cert_valid(cinfo, sign_pkey) != XEVNT_OK) {
3916 "crypto_setup: certificate %s is trusted, but not self signed.",
3922 sign_digest = cinfo->digest;
3923 if (cinfo->flags & CERT_PRIV)
3924 crypto_flags |= CRYPTO_FLAG_PRIV;
3925 crypto_flags |= cinfo->nid << 16;
3928 * Load optional leapseconds table from file "ntpkey_leap". If
3929 * the file is missing or defective, the values can later be
3930 * retrieved from a server.
3932 if (leap_file == NULL)
3933 leap_file = "ntpkey_leap";
3934 crypto_tai(leap_file);
3938 "crypto_setup: flags 0x%x host %s signature %s\n",
3939 crypto_flags, sys_hostname, OBJ_nid2ln(cinfo->nid));
3945 * crypto_config - configure data from crypto configuration command.
3949 int item, /* configuration item */
3950 char *cp /* file name */
3956 * Set random seed file name.
3958 case CRYPTO_CONF_RAND:
3959 rand_file = emalloc(strlen(cp) + 1);
3960 strcpy(rand_file, cp);
3964 * Set private key password.
3966 case CRYPTO_CONF_PW:
3967 passwd = emalloc(strlen(cp) + 1);
3972 * Set host file name.
3974 case CRYPTO_CONF_PRIV:
3975 host_file = emalloc(strlen(cp) + 1);
3976 strcpy(host_file, cp);
3980 * Set sign key file name.
3982 case CRYPTO_CONF_SIGN:
3983 sign_file = emalloc(strlen(cp) + 1);
3984 strcpy(sign_file, cp);
3988 * Set iff parameters file name.
3990 case CRYPTO_CONF_IFFPAR:
3991 iffpar_file = emalloc(strlen(cp) + 1);
3992 strcpy(iffpar_file, cp);
3996 * Set gq parameters file name.
3998 case CRYPTO_CONF_GQPAR:
3999 gqpar_file = emalloc(strlen(cp) + 1);
4000 strcpy(gqpar_file, cp);
4004 * Set mv parameters file name.
4006 case CRYPTO_CONF_MVPAR:
4007 mvpar_file = emalloc(strlen(cp) + 1);
4008 strcpy(mvpar_file, cp);
4012 * Set certificate file name.
4014 case CRYPTO_CONF_CERT:
4015 cert_file = emalloc(strlen(cp) + 1);
4016 strcpy(cert_file, cp);
4020 * Set leapseconds file name.
4022 case CRYPTO_CONF_LEAP:
4023 leap_file = emalloc(strlen(cp) + 1);
4024 strcpy(leap_file, cp);
4027 crypto_flags |= CRYPTO_FLAG_ENAB;
4030 int ntp_crypto_bs_pubkey;
4031 # endif /* OPENSSL */