1 /* $NetBSD: ntp_crypto.c,v 1.15 2009/05/20 01:37:36 christos Exp $ */
4 * ntp_crypto.c - NTP version 4 public key routines
12 #include <sys/types.h>
13 #include <sys/param.h>
18 #include "ntp_stdlib.h"
19 #include "ntp_unixtime.h"
20 #include "ntp_string.h"
21 #include <ntp_random.h>
23 #include "openssl/asn1_mac.h"
24 #include "openssl/bn.h"
25 #include "openssl/err.h"
26 #include "openssl/evp.h"
27 #include "openssl/pem.h"
28 #include "openssl/rand.h"
29 #include "openssl/x509v3.h"
32 #include "ntp_syscall.h"
33 #endif /* KERNEL_PLL */
36 * Extension field message format
38 * These are always signed and saved before sending in network byte
39 * order. They must be converted to and from host byte order for
43 * | op | len | <- extension pointer
47 * | timestamp | <- value pointer
64 * The CRYPTO_RESP bit is set to 0 for requests, 1 for responses.
65 * Requests carry the association ID of the receiver; responses carry
66 * the association ID of the sender. Some messages include only the
67 * operation/length and association ID words and so have length 8
68 * octets. Ohers include the value structure and associated value and
69 * signature fields. These messages include the timestamp, filestamp,
70 * value and signature words and so have length at least 24 octets. The
71 * signature and/or value fields can be empty, in which case the
72 * respective length words are zero. An empty value with nonempty
73 * signature is syntactically valid, but semantically questionable.
75 * The filestamp represents the time when a cryptographic data file such
76 * as a public/private key pair is created. It follows every reference
77 * depending on that file and serves as a means to obsolete earlier data
78 * of the same type. The timestamp represents the time when the
79 * cryptographic data of the message were last signed. Creation of a
80 * cryptographic data file or signing a message can occur only when the
81 * creator or signor is synchronized to an authoritative source and
82 * proventicated to a trusted authority.
84 * Note there are four conditions required for server trust. First, the
85 * public key on the certificate must be verified, which involves a
86 * number of format, content and consistency checks. Next, the server
87 * identity must be confirmed by one of four schemes: private
88 * certificate, IFF scheme, GQ scheme or certificate trail hike to a
89 * self signed trusted certificate. Finally, the server signature must
95 #define TAI_1972 10 /* initial TAI offset (s) */
96 #define MAX_LEAP 100 /* max UTC leapseconds (s) */
97 #define VALUE_LEN (6 * 4) /* min response field length */
98 #define YEAR (60 * 60 * 24 * 365) /* seconds in year */
101 * Global cryptodata in host byte order
103 u_int32 crypto_flags
= 0x0; /* status word */
106 * Global cryptodata in network byte order
108 struct cert_info
*cinfo
= NULL
; /* certificate info/value */
109 struct value hostval
; /* host value */
110 struct value pubkey
; /* public key */
111 struct value tai_leap
; /* leapseconds table */
112 EVP_PKEY
*iffpar_pkey
= NULL
; /* IFF parameters */
113 EVP_PKEY
*gqpar_pkey
= NULL
; /* GQ parameters */
114 EVP_PKEY
*mvpar_pkey
= NULL
; /* MV parameters */
115 char *iffpar_file
= NULL
; /* IFF parameters file */
116 char *gqpar_file
= NULL
; /* GQ parameters file */
117 char *mvpar_file
= NULL
; /* MV parameters file */
120 * Private cryptodata in host byte order
122 static char *passwd
= NULL
; /* private key password */
123 static EVP_PKEY
*host_pkey
= NULL
; /* host key */
124 static EVP_PKEY
*sign_pkey
= NULL
; /* sign key */
125 static const EVP_MD
*sign_digest
= NULL
; /* sign digest */
126 static u_int sign_siglen
; /* sign key length */
127 static char *rand_file
= NULL
; /* random seed file */
128 static char *host_file
= NULL
; /* host key file */
129 static char *sign_file
= NULL
; /* sign key file */
130 static char *cert_file
= NULL
; /* certificate file */
131 static char *leap_file
= NULL
; /* leapseconds file */
132 static tstamp_t if_fstamp
= 0; /* IFF filestamp */
133 static tstamp_t gq_fstamp
= 0; /* GQ file stamp */
134 static tstamp_t mv_fstamp
= 0; /* MV filestamp */
135 static u_int ident_scheme
= 0; /* server identity scheme */
140 static int crypto_verify
P((struct exten
*, struct value
*,
142 static int crypto_encrypt
P((struct exten
*, struct value
*,
144 static int crypto_alice
P((struct peer
*, struct value
*));
145 static int crypto_alice2
P((struct peer
*, struct value
*));
146 static int crypto_alice3
P((struct peer
*, struct value
*));
147 static int crypto_bob
P((struct exten
*, struct value
*));
148 static int crypto_bob2
P((struct exten
*, struct value
*));
149 static int crypto_bob3
P((struct exten
*, struct value
*));
150 static int crypto_iff
P((struct exten
*, struct peer
*));
151 static int crypto_gq
P((struct exten
*, struct peer
*));
152 static int crypto_mv
P((struct exten
*, struct peer
*));
153 static u_int crypto_send
P((struct exten
*, struct value
*));
154 static tstamp_t crypto_time
P((void));
155 static u_long asn2ntp
P((ASN1_TIME
*));
156 static struct cert_info
*cert_parse
P((u_char
*, u_int
, tstamp_t
));
157 static int cert_sign
P((struct exten
*, struct value
*));
158 static int cert_valid
P((struct cert_info
*, EVP_PKEY
*));
159 static int cert_install
P((struct exten
*, struct peer
*));
160 static void cert_free
P((struct cert_info
*));
161 static EVP_PKEY
*crypto_key
P((char *, tstamp_t
*));
162 static int bighash
P((BIGNUM
*, BIGNUM
*));
163 static struct cert_info
*crypto_cert
P((char *));
164 static void crypto_tai
P((char *));
168 readlink(char * link
, char * file
, int len
) {
174 * session_key - generate session key
176 * This routine generates a session key from the source address,
177 * destination address, key ID and private value. The value of the
178 * session key is the MD5 hash of these values, while the next key ID is
179 * the first four octets of the hash.
181 * Returns the next key ID
185 struct sockaddr_storage
*srcadr
, /* source address */
186 struct sockaddr_storage
*dstadr
, /* destination address */
187 keyid_t keyno
, /* key ID */
188 keyid_t
private, /* private value */
189 u_long lifetime
/* key lifetime */
192 EVP_MD_CTX ctx
; /* message digest context */
193 u_char dgst
[EVP_MAX_MD_SIZE
]; /* message digest */
194 keyid_t keyid
; /* key identifer */
195 u_int32 header
[10]; /* data in network byte order */
202 * Generate the session key and key ID. If the lifetime is
203 * greater than zero, install the key and call it trusted.
206 switch(srcadr
->ss_family
) {
208 header
[0] = ((struct sockaddr_in
*)srcadr
)->sin_addr
.s_addr
;
209 header
[1] = ((struct sockaddr_in
*)dstadr
)->sin_addr
.s_addr
;
210 header
[2] = htonl(keyno
);
211 header
[3] = htonl(private);
212 hdlen
= 4 * sizeof(u_int32
);
216 memcpy(&header
[0], &GET_INADDR6(*srcadr
),
217 sizeof(struct in6_addr
));
218 memcpy(&header
[4], &GET_INADDR6(*dstadr
),
219 sizeof(struct in6_addr
));
220 header
[8] = htonl(keyno
);
221 header
[9] = htonl(private);
222 hdlen
= 10 * sizeof(u_int32
);
225 EVP_DigestInit(&ctx
, EVP_md5());
226 EVP_DigestUpdate(&ctx
, (u_char
*)header
, hdlen
);
227 EVP_DigestFinal(&ctx
, dgst
, &len
);
228 memcpy(&keyid
, dgst
, 4);
229 keyid
= ntohl(keyid
);
231 MD5auth_setkey(keyno
, dgst
, len
);
232 authtrust(keyno
, lifetime
);
237 "session_key: %s > %s %08x %08x hash %08x life %lu\n",
238 stoa(srcadr
), stoa(dstadr
), keyno
,
239 private, keyid
, lifetime
);
246 * make_keylist - generate key list
250 * XEVNT_PER host certificate expired
252 * This routine constructs a pseudo-random sequence by repeatedly
253 * hashing the session key starting from a given source address,
254 * destination address, private value and the next key ID of the
255 * preceeding session key. The last entry on the list is saved along
256 * with its sequence number and public signature.
260 struct peer
*peer
, /* peer structure pointer */
261 struct interface
*dstadr
/* interface */
264 EVP_MD_CTX ctx
; /* signature context */
265 tstamp_t tstamp
; /* NTP timestamp */
266 struct autokey
*ap
; /* autokey pointer */
267 struct value
*vp
; /* value pointer */
268 keyid_t keyid
= 0; /* next key ID */
269 keyid_t cookie
; /* private value */
278 * Allocate the key list if necessary.
280 tstamp
= crypto_time();
281 if (peer
->keylist
== NULL
)
282 peer
->keylist
= emalloc(sizeof(keyid_t
) *
286 * Generate an initial key ID which is unique and greater than
290 keyid
= (ntp_random() + NTP_MAXKEY
+ 1) & ((1 <<
291 sizeof(keyid_t
)) - 1);
292 if (authhavekey(keyid
))
298 * Generate up to NTP_MAXSESSION session keys. Stop if the
299 * next one would not be unique or not a session key ID or if
300 * it would expire before the next poll. The private value
301 * included in the hash is zero if broadcast mode, the peer
302 * cookie if client mode or the host cookie if symmetric modes.
304 mpoll
= 1 << min(peer
->ppoll
, peer
->hpoll
);
305 lifetime
= min(sys_automax
, NTP_MAXSESSION
* mpoll
);
306 if (peer
->hmode
== MODE_BROADCAST
)
309 cookie
= peer
->pcookie
;
310 for (i
= 0; i
< NTP_MAXSESSION
; i
++) {
311 peer
->keylist
[i
] = keyid
;
313 keyid
= session_key(&dstadr
->sin
, &peer
->srcadr
, keyid
,
316 if (auth_havekey(keyid
) || keyid
<= NTP_MAXKEY
||
322 * Save the last session key ID, sequence number and timestamp,
323 * then sign these values for later retrieval by the clients. Be
324 * careful not to use invalid key media. Use the public values
325 * timestamp as filestamp.
329 vp
->ptr
= emalloc(sizeof(struct autokey
));
330 ap
= (struct autokey
*)vp
->ptr
;
331 ap
->seq
= htonl(peer
->keynumber
);
332 ap
->key
= htonl(keyid
);
333 vp
->tstamp
= htonl(tstamp
);
334 vp
->fstamp
= hostval
.tstamp
;
335 vp
->vallen
= htonl(sizeof(struct autokey
));
338 if (tstamp
< cinfo
->first
|| tstamp
> cinfo
->last
)
342 vp
->sig
= emalloc(sign_siglen
);
343 EVP_SignInit(&ctx
, sign_digest
);
344 EVP_SignUpdate(&ctx
, (u_char
*)vp
, 12);
345 EVP_SignUpdate(&ctx
, vp
->ptr
, sizeof(struct autokey
));
346 if (EVP_SignFinal(&ctx
, vp
->sig
, &len
, sign_pkey
))
347 vp
->siglen
= htonl(len
);
349 msyslog(LOG_ERR
, "make_keys %s\n",
350 ERR_error_string(ERR_get_error(), NULL
));
351 peer
->flags
|= FLAG_ASSOC
;
355 printf("make_keys: %d %08x %08x ts %u fs %u poll %d\n",
356 ntohl(ap
->seq
), ntohl(ap
->key
), cookie
,
357 ntohl(vp
->tstamp
), ntohl(vp
->fstamp
), peer
->hpoll
);
364 * crypto_recv - parse extension fields
366 * This routine is called when the packet has been matched to an
367 * association and passed sanity, format and MAC checks. We believe the
368 * extension field values only if the field has proper format and
369 * length, the timestamp and filestamp are valid and the signature has
370 * valid length and is verified. There are a few cases where some values
371 * are believed even if the signature fails, but only if the proventic
376 struct peer
*peer
, /* peer structure pointer */
377 struct recvbuf
*rbufp
/* packet buffer pointer */
380 const EVP_MD
*dp
; /* message digest algorithm */
381 u_int32
*pkt
; /* receive packet pointer */
382 struct autokey
*ap
, *bp
; /* autokey pointer */
383 struct exten
*ep
, *fp
; /* extension pointers */
384 int has_mac
; /* length of MAC field */
385 int authlen
; /* offset of MAC field */
386 associd_t associd
; /* association ID */
387 tstamp_t tstamp
= 0; /* timestamp */
388 tstamp_t fstamp
= 0; /* filestamp */
389 u_int len
; /* extension field length */
390 u_int code
; /* extension field opcode */
391 u_int vallen
= 0; /* value length */
392 X509
*cert
; /* X509 certificate */
393 char statstr
[NTP_MAXSTRLEN
]; /* statistics for filegen */
394 keyid_t cookie
; /* crumbles */
395 int hismode
; /* packet mode */
401 * Initialize. Note that the packet has already been checked for
402 * valid format and extension field lengths. First extract the
403 * field length, command code and association ID in host byte
404 * order. These are used with all commands and modes. Then check
405 * the version number, which must be 2, and length, which must
406 * be at least 8 for requests and VALUE_LEN (24) for responses.
407 * Packets that fail either test sink without a trace. The
408 * association ID is saved only if nonzero.
410 authlen
= LEN_PKT_NOMAC
;
411 hismode
= (int)PKT_MODE((&rbufp
->recv_pkt
)->li_vn_mode
);
412 while ((has_mac
= rbufp
->recv_length
- authlen
) > MAX_MAC_LEN
) {
413 pkt
= (u_int32
*)&rbufp
->recv_pkt
+ authlen
/ 4;
414 ep
= (struct exten
*)pkt
;
415 code
= ntohl(ep
->opcode
) & 0xffff0000;
416 len
= ntohl(ep
->opcode
) & 0x0000ffff;
417 associd
= (associd_t
) ntohl(pkt
[1]);
422 "crypto_recv: flags 0x%x ext offset %d len %u code 0x%x assocID %d\n",
423 peer
->crypto
, authlen
, len
, code
>> 16,
428 * Check version number and field length. If bad,
429 * quietly ignore the packet.
431 if (((code
>> 24) & 0x3f) != CRYPTO_VN
|| len
< 8) {
432 sys_unknownversion
++;
433 code
|= CRYPTO_ERROR
;
437 * Little vulnerability bandage here. If a perp tosses a
438 * fake association ID over the fence, we better toss it
439 * out. Only the first one counts.
441 if (code
& CRYPTO_RESP
) {
442 if (peer
->assoc
== 0)
443 peer
->assoc
= associd
;
444 else if (peer
->assoc
!= associd
)
445 code
|= CRYPTO_ERROR
;
447 if (len
>= VALUE_LEN
) {
448 tstamp
= ntohl(ep
->tstamp
);
449 fstamp
= ntohl(ep
->fstamp
);
450 vallen
= ntohl(ep
->vallen
);
455 * Install status word, host name, signature scheme and
456 * association ID. In OpenSSL the signature algorithm is
457 * bound to the digest algorithm, so the NID completely
458 * defines the signature scheme. Note the request and
459 * response are identical, but neither is validated by
460 * signature. The request is processed here only in
461 * symmetric modes. The server name field might be
462 * useful to implement access controls in future.
467 * If the machine is running when this message
468 * arrives, the other fellow has reset and so
469 * must we. Otherwise, pass the extension field
470 * to the transmit side.
478 temp32
= CRYPTO_RESP
;
479 fp
->opcode
|= htonl(temp32
);
483 case CRYPTO_ASSOC
| CRYPTO_RESP
:
486 * Discard the message if it has already been
487 * stored or the message has been amputated.
492 if (vallen
== 0 || vallen
> MAXHOSTNAME
||
493 len
< VALUE_LEN
+ vallen
) {
499 * Check the identity schemes are compatible. If
500 * the client has PC, the server must have PC,
501 * in which case the server public key and
502 * identity are presumed valid, so we skip the
503 * certificate and identity exchanges and move
504 * immediately to the cookie exchange which
505 * confirms the server signature.
510 "crypto_recv: ident host 0x%x server 0x%x\n",
511 crypto_flags
, fstamp
);
513 temp32
= (crypto_flags
| ident_scheme
) &
514 fstamp
& CRYPTO_FLAG_MASK
;
515 if (crypto_flags
& CRYPTO_FLAG_PRIV
) {
516 if (!(fstamp
& CRYPTO_FLAG_PRIV
)) {
521 fstamp
|= CRYPTO_FLAG_VALID
|
526 * In symmetric modes it is an error if either
527 * peer requests identity and the other peer
528 * does not support it.
530 } else if ((hismode
== MODE_ACTIVE
|| hismode
==
531 MODE_PASSIVE
) && ((crypto_flags
| fstamp
) &
532 CRYPTO_FLAG_MASK
) && !temp32
) {
536 * It is an error if the client requests
537 * identity and the server does not support it.
539 } else if (hismode
== MODE_CLIENT
&& (fstamp
&
540 CRYPTO_FLAG_MASK
) && !temp32
) {
546 * Otherwise, the identity scheme(s) are those
547 * that both client and server support.
549 fstamp
= temp32
| (fstamp
& ~CRYPTO_FLAG_MASK
);
552 * Discard the message if the signature digest
553 * NID is not supported.
555 temp32
= (fstamp
>> 16) & 0xffff;
557 (const EVP_MD
*)EVP_get_digestbynid(temp32
);
564 * Save status word, host name and message
565 * digest/signature type.
567 peer
->crypto
= fstamp
;
569 peer
->subject
= emalloc(vallen
+ 1);
570 memcpy(peer
->subject
, ep
->pkt
, vallen
);
571 peer
->subject
[vallen
] = '\0';
572 peer
->issuer
= emalloc(vallen
+ 1);
573 strcpy(peer
->issuer
, peer
->subject
);
574 temp32
= (fstamp
>> 16) & 0xffff;
575 snprintf(statstr
, NTP_MAXSTRLEN
,
576 "flags 0x%x host %s signature %s", fstamp
,
577 peer
->subject
, OBJ_nid2ln(temp32
));
578 record_crypto_stats(&peer
->srcadr
, statstr
);
581 printf("crypto_recv: %s\n", statstr
);
586 * Decode X509 certificate in ASN.1 format and extract
587 * the data containing, among other things, subject
588 * name and public key. In the default identification
589 * scheme, the certificate trail is followed to a self
590 * signed trusted certificate.
592 case CRYPTO_CERT
| CRYPTO_RESP
:
595 * Discard the message if invalid.
597 if ((rval
= crypto_verify(ep
, NULL
, peer
)) !=
602 * Scan the certificate list to delete old
603 * versions and link the newest version first on
606 if ((rval
= cert_install(ep
, peer
)) != XEVNT_OK
)
610 * If we snatch the certificate before the
611 * server certificate has been signed by its
612 * server, it will be self signed. When it is,
613 * we chase the certificate issuer, which the
614 * server has, and keep going until a self
615 * signed trusted certificate is found. Be sure
616 * to update the issuer field, since it may
619 if (peer
->issuer
!= NULL
)
621 peer
->issuer
= emalloc(strlen(cinfo
->issuer
) +
623 strcpy(peer
->issuer
, cinfo
->issuer
);
626 * We plug in the public key and lifetime from
627 * the first certificate received. However, note
628 * that this certificate might not be signed by
629 * the server, so we can't check the
630 * signature/digest NID.
632 if (peer
->pkey
== NULL
) {
633 ptr
= (u_char
*)cinfo
->cert
.ptr
;
634 cert
= d2i_X509(NULL
, &ptr
,
635 ntohl(cinfo
->cert
.vallen
));
636 peer
->pkey
= X509_get_pubkey(cert
);
639 peer
->flash
&= ~TEST8
;
641 snprintf(statstr
, NTP_MAXSTRLEN
,
642 "cert %s 0x%x %s (%u) fs %u",
643 cinfo
->subject
, cinfo
->flags
,
644 OBJ_nid2ln(temp32
), temp32
,
646 record_crypto_stats(&peer
->srcadr
, statstr
);
649 printf("crypto_recv: %s\n", statstr
);
654 * Schnorr (IFF)identity scheme. This scheme is designed
655 * for use with shared secret group keys and where the
656 * certificate may be generated by a third party. The
657 * client sends a challenge to the server, which
658 * performs a calculation and returns the result. A
659 * positive result is possible only if both client and
660 * server contain the same secret group key.
662 case CRYPTO_IFF
| CRYPTO_RESP
:
665 * Discard the message if invalid or certificate
668 if (!(peer
->crypto
& CRYPTO_FLAG_VALID
)) {
672 if ((rval
= crypto_verify(ep
, NULL
, peer
)) !=
677 * If the the challenge matches the response,
678 * the certificate public key, as well as the
679 * server public key, signatyre and identity are
680 * all verified at the same time. The server is
681 * declared trusted, so we skip further
682 * certificate stages and move immediately to
685 if ((rval
= crypto_iff(ep
, peer
)) != XEVNT_OK
)
688 peer
->crypto
|= CRYPTO_FLAG_VRFY
|
690 peer
->flash
&= ~TEST8
;
691 snprintf(statstr
, NTP_MAXSTRLEN
, "iff fs %u",
693 record_crypto_stats(&peer
->srcadr
, statstr
);
696 printf("crypto_recv: %s\n", statstr
);
701 * Guillou-Quisquater (GQ) identity scheme. This scheme
702 * is designed for use with public certificates carrying
703 * the GQ public key in an extension field. The client
704 * sends a challenge to the server, which performs a
705 * calculation and returns the result. A positive result
706 * is possible only if both client and server contain
707 * the same group key and the server has the matching GQ
710 case CRYPTO_GQ
| CRYPTO_RESP
:
713 * Discard the message if invalid or certificate
716 if (!(peer
->crypto
& CRYPTO_FLAG_VALID
)) {
720 if ((rval
= crypto_verify(ep
, NULL
, peer
)) !=
725 * If the the challenge matches the response,
726 * the certificate public key, as well as the
727 * server public key, signatyre and identity are
728 * all verified at the same time. The server is
729 * declared trusted, so we skip further
730 * certificate stages and move immediately to
733 if ((rval
= crypto_gq(ep
, peer
)) != XEVNT_OK
)
736 peer
->crypto
|= CRYPTO_FLAG_VRFY
|
738 peer
->flash
&= ~TEST8
;
739 snprintf(statstr
, NTP_MAXSTRLEN
, "gq fs %u",
741 record_crypto_stats(&peer
->srcadr
, statstr
);
744 printf("crypto_recv: %s\n", statstr
);
751 case CRYPTO_MV
| CRYPTO_RESP
:
754 * Discard the message if invalid or certificate
757 if (!(peer
->crypto
& CRYPTO_FLAG_VALID
)) {
761 if ((rval
= crypto_verify(ep
, NULL
, peer
)) !=
766 * If the the challenge matches the response,
767 * the certificate public key, as well as the
768 * server public key, signatyre and identity are
769 * all verified at the same time. The server is
770 * declared trusted, so we skip further
771 * certificate stages and move immediately to
774 if ((rval
= crypto_mv(ep
, peer
)) != XEVNT_OK
)
777 peer
->crypto
|= CRYPTO_FLAG_VRFY
|
779 peer
->flash
&= ~TEST8
;
780 snprintf(statstr
, NTP_MAXSTRLEN
, "mv fs %u",
782 record_crypto_stats(&peer
->srcadr
, statstr
);
785 printf("crypto_recv: %s\n", statstr
);
790 * Cookie request in symmetric modes. Roll a random
791 * cookie and install in symmetric mode. Encrypt for the
792 * response, which is transmitted later.
797 * Discard the message if invalid or certificate
800 if (!(peer
->crypto
& CRYPTO_FLAG_VALID
)) {
804 if ((rval
= crypto_verify(ep
, NULL
, peer
)) !=
809 * Pass the extension field to the transmit
810 * side. If already agreed, walk away.
814 temp32
= CRYPTO_RESP
;
815 fp
->opcode
|= htonl(temp32
);
817 if (peer
->crypto
& CRYPTO_FLAG_AGREE
) {
818 peer
->flash
&= ~TEST8
;
823 * Install cookie values and light the cookie
824 * bit. The transmit side will pick up and
825 * encrypt it for the response.
828 peer
->cookval
.tstamp
= ep
->tstamp
;
829 peer
->cookval
.fstamp
= ep
->fstamp
;
830 RAND_bytes((u_char
*)&peer
->pcookie
, 4);
831 peer
->crypto
&= ~CRYPTO_FLAG_AUTO
;
832 peer
->crypto
|= CRYPTO_FLAG_AGREE
;
833 peer
->flash
&= ~TEST8
;
834 snprintf(statstr
, NTP_MAXSTRLEN
, "cook %x ts %u fs %u",
835 peer
->pcookie
, ntohl(ep
->tstamp
),
837 record_crypto_stats(&peer
->srcadr
, statstr
);
840 printf("crypto_recv: %s\n", statstr
);
845 * Cookie response in client and symmetric modes. If the
846 * cookie bit is set, the working cookie is the EXOR of
847 * the current and new values.
849 case CRYPTO_COOK
| CRYPTO_RESP
:
852 * Discard the message if invalid or identity
853 * not confirmed or signature not verified with
854 * respect to the cookie values.
856 if (!(peer
->crypto
& CRYPTO_FLAG_VRFY
)) {
860 if ((rval
= crypto_verify(ep
, &peer
->cookval
,
865 * Decrypt the cookie, hunting all the time for
868 if (vallen
== (u_int
) EVP_PKEY_size(host_pkey
)) {
869 RSA_private_decrypt(vallen
,
873 RSA_PKCS1_OAEP_PADDING
);
874 cookie
= ntohl(temp32
);
881 * Install cookie values and light the cookie
882 * bit. If this is not broadcast client mode, we
886 peer
->cookval
.tstamp
= ep
->tstamp
;
887 peer
->cookval
.fstamp
= ep
->fstamp
;
888 if (peer
->crypto
& CRYPTO_FLAG_AGREE
)
889 peer
->pcookie
^= cookie
;
891 peer
->pcookie
= cookie
;
892 if (peer
->hmode
== MODE_CLIENT
&&
893 !(peer
->cast_flags
& MDF_BCLNT
))
894 peer
->crypto
|= CRYPTO_FLAG_AUTO
;
896 peer
->crypto
&= ~CRYPTO_FLAG_AUTO
;
897 peer
->crypto
|= CRYPTO_FLAG_AGREE
;
898 peer
->flash
&= ~TEST8
;
899 snprintf(statstr
, NTP_MAXSTRLEN
, "cook %x ts %u fs %u",
900 peer
->pcookie
, ntohl(ep
->tstamp
),
902 record_crypto_stats(&peer
->srcadr
, statstr
);
905 printf("crypto_recv: %s\n", statstr
);
910 * Install autokey values in broadcast client and
911 * symmetric modes. We have to do this every time the
912 * sever/peer cookie changes or a new keylist is
913 * rolled. Ordinarily, this is automatic as this message
914 * is piggybacked on the first NTP packet sent upon
915 * either of these events. Note that a broadcast client
916 * or symmetric peer can receive this response without a
919 case CRYPTO_AUTO
| CRYPTO_RESP
:
922 * Discard the message if invalid or identity
923 * not confirmed or signature not verified with
924 * respect to the receive autokey values.
926 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
&= ~TEST8
;
950 snprintf(statstr
, NTP_MAXSTRLEN
,
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 * X509 certificate sign response. Validate the
963 * certificate signed by the server and install. Later
964 * this can be provided to clients of this server in
965 * lieu of the self signed certificate in order to
966 * validate the public key.
968 case CRYPTO_SIGN
| CRYPTO_RESP
:
971 * Discard the message if invalid or not
974 if (!(peer
->crypto
& CRYPTO_FLAG_PROV
)) {
978 if ((rval
= crypto_verify(ep
, NULL
, peer
)) !=
983 * Scan the certificate list to delete old
984 * versions and link the newest version first on
987 if ((rval
= cert_install(ep
, peer
)) != XEVNT_OK
)
990 peer
->crypto
|= CRYPTO_FLAG_SIGN
;
991 peer
->flash
&= ~TEST8
;
993 snprintf(statstr
, NTP_MAXSTRLEN
,
994 "sign %s 0x%x %s (%u) fs %u",
995 cinfo
->issuer
, cinfo
->flags
,
996 OBJ_nid2ln(temp32
), temp32
,
998 record_crypto_stats(&peer
->srcadr
, statstr
);
1001 printf("crypto_recv: %s\n", statstr
);
1006 * Install leapseconds table in symmetric modes. This
1007 * table is proventicated to the NIST primary servers,
1008 * either by copying the file containing the table from
1009 * a NIST server to a trusted server or directly using
1010 * this protocol. While the entire table is installed at
1011 * the server, presently only the current TAI offset is
1012 * provided via the kernel to other applications.
1017 * Discard the message if invalid.
1019 if ((rval
= crypto_verify(ep
, NULL
, peer
)) !=
1024 * Pass the extension field to the transmit
1025 * side. Continue below if a leapseconds table
1026 * accompanies the message.
1029 memcpy(fp
, ep
, len
);
1030 temp32
= CRYPTO_RESP
;
1031 fp
->opcode
|= htonl(temp32
);
1033 if (len
<= VALUE_LEN
) {
1034 peer
->flash
&= ~TEST8
;
1039 case CRYPTO_TAI
| CRYPTO_RESP
:
1042 * If this is a response, discard the message if
1043 * signature not verified with respect to the
1044 * leapsecond table values.
1046 if (peer
->cmmd
== NULL
) {
1047 if ((rval
= crypto_verify(ep
,
1048 &peer
->tai_leap
, peer
)) != XEVNT_OK
)
1053 * Initialize peer variables with latest update.
1055 peer
->tai_leap
.tstamp
= ep
->tstamp
;
1056 peer
->tai_leap
.fstamp
= ep
->fstamp
;
1057 peer
->tai_leap
.vallen
= ep
->vallen
;
1060 * Install the new table if there is no stored
1061 * table or the new table is more recent than
1062 * the stored table. Since a filestamp may have
1063 * changed, recompute the signatures.
1065 if (ntohl(peer
->tai_leap
.fstamp
) >
1066 ntohl(tai_leap
.fstamp
)) {
1067 tai_leap
.fstamp
= ep
->fstamp
;
1068 tai_leap
.vallen
= ep
->vallen
;
1069 if (tai_leap
.ptr
!= NULL
)
1071 tai_leap
.ptr
= emalloc(vallen
);
1072 memcpy(tai_leap
.ptr
, ep
->pkt
, vallen
);
1075 crypto_flags
|= CRYPTO_FLAG_TAI
;
1076 peer
->crypto
|= CRYPTO_FLAG_LEAP
;
1077 peer
->flash
&= ~TEST8
;
1078 snprintf(statstr
, NTP_MAXSTRLEN
,
1079 "leap %u ts %u fs %u", vallen
,
1080 ntohl(ep
->tstamp
), ntohl(ep
->fstamp
));
1081 record_crypto_stats(&peer
->srcadr
, statstr
);
1084 printf("crypto_recv: %s\n", statstr
);
1089 * We come here in symmetric modes for miscellaneous
1090 * commands that have value fields but are processed on
1091 * the transmit side. All we need do here is check for
1092 * valid field length. Remaining checks are below and on
1093 * the transmit side.
1100 if (len
< VALUE_LEN
) {
1107 * We come here for miscellaneous requests and unknown
1108 * requests and responses. If an unknown response or
1109 * error, forget it. If a request, save the extension
1110 * field for later. Unknown requests will be caught on
1111 * the transmit side.
1114 if (code
& (CRYPTO_RESP
| CRYPTO_ERROR
)) {
1116 } else if ((rval
= crypto_verify(ep
, NULL
,
1117 peer
)) == XEVNT_OK
) {
1119 memcpy(fp
, ep
, len
);
1120 temp32
= CRYPTO_RESP
;
1121 fp
->opcode
|= htonl(temp32
);
1127 * We don't log length/format/timestamp errors and
1128 * duplicates, which are log clogging vulnerabilities.
1129 * The first error found terminates the extension field
1130 * scan and we return the laundry to the caller. A
1131 * length/format/timestamp error on transmit is
1132 * cheerfully ignored, as the message is not sent.
1134 if (rval
> XEVNT_TSP
) {
1135 snprintf(statstr
, NTP_MAXSTRLEN
,
1136 "error %x opcode %x ts %u fs %u", rval
,
1137 code
, tstamp
, fstamp
);
1138 record_crypto_stats(&peer
->srcadr
, statstr
);
1139 report_event(rval
, peer
);
1142 printf("crypto_recv: %s\n", statstr
);
1146 } else if (rval
> XEVNT_OK
&& (code
& CRYPTO_RESP
)) {
1156 * crypto_xmit - construct extension fields
1158 * This routine is called both when an association is configured and
1159 * when one is not. The only case where this matters is to retrieve the
1160 * autokey information, in which case the caller has to provide the
1161 * association ID to match the association.
1163 * Returns length of extension field.
1167 struct pkt
*xpkt
, /* transmit packet pointer */
1168 struct sockaddr_storage
*srcadr_sin
, /* active runway */
1169 int start
, /* offset to extension field */
1170 struct exten
*ep
, /* extension pointer */
1171 keyid_t cookie
/* session cookie */
1174 u_int32
*pkt
; /* packet pointer */
1175 struct peer
*peer
; /* peer structure pointer */
1176 u_int opcode
; /* extension field opcode */
1177 struct exten
*fp
; /* extension pointers */
1178 struct cert_info
*cp
, *xp
; /* certificate info/value pointer */
1179 char certname
[MAXHOSTNAME
+ 1]; /* subject name buffer */
1180 char statstr
[NTP_MAXSTRLEN
]; /* statistics for filegen */
1190 * Generate the requested extension field request code, length
1191 * and association ID. If this is a response and the host is not
1192 * synchronized, light the error bit and go home.
1194 pkt
= (u_int32
*)xpkt
+ start
/ 4;
1195 fp
= (struct exten
*)pkt
;
1196 opcode
= ntohl(ep
->opcode
);
1197 associd
= (associd_t
) ntohl(ep
->associd
);
1198 fp
->associd
= htonl(associd
);
1201 tstamp
= crypto_time();
1202 switch (opcode
& 0xffff0000) {
1205 * Send association request and response with status word and
1206 * host name. Note, this message is not signed and the filestamp
1207 * contains only the status word.
1209 case CRYPTO_ASSOC
| CRYPTO_RESP
:
1210 len
+= crypto_send(fp
, &hostval
);
1211 fp
->fstamp
= htonl(crypto_flags
);
1215 len
+= crypto_send(fp
, &hostval
);
1216 fp
->fstamp
= htonl(crypto_flags
| ident_scheme
);
1220 * Send certificate request. Use the values from the extension
1224 memset(&vtemp
, 0, sizeof(vtemp
));
1225 vtemp
.tstamp
= ep
->tstamp
;
1226 vtemp
.fstamp
= ep
->fstamp
;
1227 vtemp
.vallen
= ep
->vallen
;
1228 vtemp
.ptr
= (u_char
*)ep
->pkt
;
1229 len
+= crypto_send(fp
, &vtemp
);
1233 * Send certificate response or sign request. Use the values
1234 * from the certificate cache. If the request contains no
1235 * subject name, assume the name of this host. This is for
1236 * backwards compatibility. Private certificates are never sent.
1239 case CRYPTO_CERT
| CRYPTO_RESP
:
1240 vallen
= ntohl(ep
->vallen
);
1242 strcpy(certname
, sys_hostname
);
1243 } else if (vallen
== 0 || vallen
> MAXHOSTNAME
) {
1248 memcpy(certname
, ep
->pkt
, vallen
);
1249 certname
[vallen
] = '\0';
1253 * Find all certificates with matching subject. If a
1254 * self-signed, trusted certificate is found, use that.
1255 * If not, use the first one with matching subject. A
1256 * private certificate is never divulged or signed.
1259 for (cp
= cinfo
; cp
!= NULL
; cp
= cp
->link
) {
1260 if (cp
->flags
& CERT_PRIV
)
1263 if (strcmp(certname
, cp
->subject
) == 0) {
1266 if (strcmp(certname
, cp
->issuer
) ==
1267 0 && cp
->flags
& CERT_TRUST
) {
1275 * Be careful who you trust. If not yet synchronized,
1276 * give back an empty response. If certificate not found
1277 * or beyond the lifetime, return an error. This is to
1278 * avoid a bad dude trying to get an expired certificate
1279 * re-signed. Otherwise, send it.
1281 * Note the timestamp and filestamp are taken from the
1282 * certificate value structure. For all certificates the
1283 * timestamp is the latest signature update time. For
1284 * host and imported certificates the filestamp is the
1285 * creation epoch. For signed certificates the filestamp
1286 * is the creation epoch of the trusted certificate at
1287 * the base of the certificate trail. In principle, this
1288 * allows strong checking for signature masquerade.
1295 else if (tstamp
< xp
->first
|| tstamp
> xp
->last
)
1298 len
+= crypto_send(fp
, &xp
->cert
);
1302 * Send challenge in Schnorr (IFF) identity scheme.
1305 if ((peer
= findpeerbyassoc(ep
->pkt
[0])) == NULL
) {
1309 if ((rval
= crypto_alice(peer
, &vtemp
)) == XEVNT_OK
) {
1310 len
+= crypto_send(fp
, &vtemp
);
1316 * Send response in Schnorr (IFF) identity scheme.
1318 case CRYPTO_IFF
| CRYPTO_RESP
:
1319 if ((rval
= crypto_bob(ep
, &vtemp
)) == XEVNT_OK
) {
1320 len
+= crypto_send(fp
, &vtemp
);
1326 * Send challenge in Guillou-Quisquater (GQ) identity scheme.
1329 if ((peer
= findpeerbyassoc(ep
->pkt
[0])) == NULL
) {
1333 if ((rval
= crypto_alice2(peer
, &vtemp
)) == XEVNT_OK
) {
1334 len
+= crypto_send(fp
, &vtemp
);
1340 * Send response in Guillou-Quisquater (GQ) identity scheme.
1342 case CRYPTO_GQ
| CRYPTO_RESP
:
1343 if ((rval
= crypto_bob2(ep
, &vtemp
)) == XEVNT_OK
) {
1344 len
+= crypto_send(fp
, &vtemp
);
1350 * Send challenge in MV identity scheme.
1353 if ((peer
= findpeerbyassoc(ep
->pkt
[0])) == NULL
) {
1357 if ((rval
= crypto_alice3(peer
, &vtemp
)) == XEVNT_OK
) {
1358 len
+= crypto_send(fp
, &vtemp
);
1364 * Send response in MV identity scheme.
1366 case CRYPTO_MV
| CRYPTO_RESP
:
1367 if ((rval
= crypto_bob3(ep
, &vtemp
)) == XEVNT_OK
) {
1368 len
+= crypto_send(fp
, &vtemp
);
1374 * Send certificate sign response. The integrity of the request
1375 * certificate has already been verified on the receive side.
1376 * Sign the response using the local server key. Use the
1377 * filestamp from the request and use the timestamp as the
1378 * current time. Light the error bit if the certificate is
1379 * invalid or contains an unverified signature.
1381 case CRYPTO_SIGN
| CRYPTO_RESP
:
1382 if ((rval
= cert_sign(ep
, &vtemp
)) == XEVNT_OK
)
1383 len
+= crypto_send(fp
, &vtemp
);
1388 * Send public key and signature. Use the values from the public
1392 len
+= crypto_send(fp
, &pubkey
);
1396 * Encrypt and send cookie and signature. Light the error bit if
1397 * anything goes wrong.
1399 case CRYPTO_COOK
| CRYPTO_RESP
:
1400 if ((opcode
& 0xffff) < VALUE_LEN
) {
1404 if (PKT_MODE(xpkt
->li_vn_mode
) == MODE_SERVER
) {
1407 if ((peer
= findpeerbyassoc(associd
)) == NULL
) {
1411 tcookie
= peer
->pcookie
;
1413 if ((rval
= crypto_encrypt(ep
, &vtemp
, &tcookie
)) ==
1415 len
+= crypto_send(fp
, &vtemp
);
1420 * Find peer and send autokey data and signature in broadcast
1421 * server and symmetric modes. Use the values in the autokey
1422 * structure. If no association is found, either the server has
1423 * restarted with new associations or some perp has replayed an
1424 * old message, in which case light the error bit.
1426 case CRYPTO_AUTO
| CRYPTO_RESP
:
1427 if ((peer
= findpeerbyassoc(associd
)) == NULL
) {
1431 peer
->flags
&= ~FLAG_ASSOC
;
1432 len
+= crypto_send(fp
, &peer
->sndval
);
1436 * Send leapseconds table and signature. Use the values from the
1437 * tai structure. If no table has been loaded, just send an
1441 case CRYPTO_TAI
| CRYPTO_RESP
:
1442 if (crypto_flags
& CRYPTO_FLAG_TAI
)
1443 len
+= crypto_send(fp
, &tai_leap
);
1447 * Default - Fall through for requests; for unknown responses,
1451 if (opcode
& CRYPTO_RESP
)
1456 * In case of error, flame the log. If a request, toss the
1457 * puppy; if a response, return so the sender can flame, too.
1459 if (rval
!= XEVNT_OK
) {
1460 opcode
|= CRYPTO_ERROR
;
1461 snprintf(statstr
, NTP_MAXSTRLEN
,
1462 "error %x opcode %x", rval
, opcode
);
1463 record_crypto_stats(srcadr_sin
, statstr
);
1464 report_event(rval
, NULL
);
1467 printf("crypto_xmit: %s\n", statstr
);
1469 if (!(opcode
& CRYPTO_RESP
))
1474 * Round up the field length to a multiple of 8 bytes and save
1475 * the request code and length.
1477 len
= ((len
+ 7) / 8) * 8;
1478 fp
->opcode
= htonl((opcode
& 0xffff0000) | len
);
1482 "crypto_xmit: flags 0x%x ext offset %d len %u code 0x%x assocID %d\n",
1483 crypto_flags
, start
, len
, opcode
>> 16, associd
);
1490 * crypto_verify - parse and verify the extension field and value
1494 * XEVNT_LEN bad field format or length
1495 * XEVNT_TSP bad timestamp
1496 * XEVNT_FSP bad filestamp
1497 * XEVNT_PUB bad or missing public key
1498 * XEVNT_SGL bad signature length
1499 * XEVNT_SIG signature not verified
1500 * XEVNT_ERR protocol error
1504 struct exten
*ep
, /* extension pointer */
1505 struct value
*vp
, /* value pointer */
1506 struct peer
*peer
/* peer structure pointer */
1509 EVP_PKEY
*pkey
; /* server public key */
1510 EVP_MD_CTX ctx
; /* signature context */
1511 tstamp_t tstamp
, tstamp1
= 0; /* timestamp */
1512 tstamp_t fstamp
, fstamp1
= 0; /* filestamp */
1513 u_int vallen
; /* value length */
1514 u_int siglen
; /* signature length */
1519 * We require valid opcode and field lengths, timestamp,
1520 * filestamp, public key, digest, signature length and
1521 * signature, where relevant. Note that preliminary length
1522 * checks are done in the main loop.
1524 len
= ntohl(ep
->opcode
) & 0x0000ffff;
1525 opcode
= ntohl(ep
->opcode
) & 0xffff0000;
1528 * Check for valid operation code and protocol. The opcode must
1529 * not have the error bit set. If a response, it must have a
1530 * value header. If a request and does not contain a value
1531 * header, no need for further checking.
1533 if (opcode
& CRYPTO_ERROR
)
1536 if (opcode
& CRYPTO_RESP
) {
1537 if (len
< VALUE_LEN
)
1540 if (len
< VALUE_LEN
)
1545 * We have a value header. Check for valid field lengths. The
1546 * field length must be long enough to contain the value header,
1547 * value and signature. Note both the value and signature fields
1548 * are rounded up to the next word.
1550 vallen
= ntohl(ep
->vallen
);
1551 i
= (vallen
+ 3) / 4;
1552 siglen
= ntohl(ep
->pkt
[i
++]);
1553 if (len
< VALUE_LEN
+ ((vallen
+ 3) / 4) * 4 + ((siglen
+ 3) /
1558 * Punt if this is a response with no data. Punt if this is a
1559 * request and a previous response is pending.
1561 if (opcode
& CRYPTO_RESP
) {
1565 if (peer
->cmmd
!= NULL
)
1570 * Check for valid timestamp and filestamp. If the timestamp is
1571 * zero, the sender is not synchronized and signatures are
1572 * disregarded. If not, the timestamp must not precede the
1573 * filestamp. The timestamp and filestamp must not precede the
1574 * corresponding values in the value structure, if present. Once
1575 * the autokey values have been installed, the timestamp must
1576 * always be later than the corresponding value in the value
1577 * structure. Duplicate timestamps are illegal once the cookie
1578 * has been validated.
1580 tstamp
= ntohl(ep
->tstamp
);
1581 fstamp
= ntohl(ep
->fstamp
);
1585 if (tstamp
< fstamp
)
1589 tstamp1
= ntohl(vp
->tstamp
);
1590 fstamp1
= ntohl(vp
->fstamp
);
1591 if ((tstamp
< tstamp1
|| (tstamp
== tstamp1
&&
1592 (peer
->crypto
& CRYPTO_FLAG_AUTO
))))
1595 if ((tstamp
< fstamp1
|| fstamp
< fstamp1
))
1600 * Check for valid signature length, public key and digest
1603 if (crypto_flags
& peer
->crypto
& CRYPTO_FLAG_PRIV
)
1607 if (siglen
== 0 || pkey
== NULL
|| peer
->digest
== NULL
)
1610 if (siglen
!= (u_int
)EVP_PKEY_size(pkey
))
1614 * Darn, I thought we would never get here. Verify the
1615 * signature. If the identity exchange is verified, light the
1616 * proventic bit. If no client identity scheme is specified,
1617 * avoid doing the sign exchange.
1619 EVP_VerifyInit(&ctx
, peer
->digest
);
1620 EVP_VerifyUpdate(&ctx
, (u_char
*)&ep
->tstamp
, vallen
+ 12);
1621 if (EVP_VerifyFinal(&ctx
, (u_char
*)&ep
->pkt
[i
], siglen
, pkey
) <= 0)
1624 if (peer
->crypto
& CRYPTO_FLAG_VRFY
) {
1625 peer
->crypto
|= CRYPTO_FLAG_PROV
;
1626 if (!(crypto_flags
& CRYPTO_FLAG_MASK
))
1627 peer
->crypto
|= CRYPTO_FLAG_SIGN
;
1634 * crypto_encrypt - construct encrypted cookie and signature from
1635 * extension field and cookie
1639 * XEVNT_PUB bad or missing public key
1640 * XEVNT_CKY bad or missing cookie
1641 * XEVNT_PER host certificate expired
1645 struct exten
*ep
, /* extension pointer */
1646 struct value
*vp
, /* value pointer */
1647 keyid_t
*cookie
/* server cookie */
1650 EVP_PKEY
*pkey
; /* public key */
1651 EVP_MD_CTX ctx
; /* signature context */
1652 tstamp_t tstamp
; /* NTP timestamp */
1658 * Extract the public key from the request.
1660 len
= ntohl(ep
->vallen
);
1661 ptr
= (u_char
*)ep
->pkt
;
1662 pkey
= d2i_PublicKey(EVP_PKEY_RSA
, NULL
, &ptr
, len
);
1664 msyslog(LOG_ERR
, "crypto_encrypt %s\n",
1665 ERR_error_string(ERR_get_error(), NULL
));
1670 * Encrypt the cookie, encode in ASN.1 and sign.
1672 tstamp
= crypto_time();
1673 memset(vp
, 0, sizeof(struct value
));
1674 vp
->tstamp
= htonl(tstamp
);
1675 vp
->fstamp
= hostval
.tstamp
;
1676 len
= EVP_PKEY_size(pkey
);
1677 vp
->vallen
= htonl(len
);
1678 vp
->ptr
= emalloc(len
);
1679 temp32
= htonl(*cookie
);
1680 if (!RSA_public_encrypt(4, (u_char
*)&temp32
, vp
->ptr
,
1681 pkey
->pkey
.rsa
, RSA_PKCS1_OAEP_PADDING
)) {
1682 msyslog(LOG_ERR
, "crypto_encrypt %s\n",
1683 ERR_error_string(ERR_get_error(), NULL
));
1684 EVP_PKEY_free(pkey
);
1687 EVP_PKEY_free(pkey
);
1692 if (tstamp
< cinfo
->first
|| tstamp
> cinfo
->last
)
1695 vp
->sig
= emalloc(sign_siglen
);
1696 EVP_SignInit(&ctx
, sign_digest
);
1697 EVP_SignUpdate(&ctx
, (u_char
*)&vp
->tstamp
, 12);
1698 EVP_SignUpdate(&ctx
, vp
->ptr
, len
);
1699 if (EVP_SignFinal(&ctx
, vp
->sig
, &len
, sign_pkey
))
1700 vp
->siglen
= htonl(len
);
1706 * crypto_ident - construct extension field for identity scheme
1708 * This routine determines which identity scheme is in use and
1709 * constructs an extension field for that scheme.
1713 struct peer
*peer
/* peer structure pointer */
1716 char filename
[MAXFILENAME
+ 1];
1719 * If the server identity has already been verified, no further
1720 * action is necessary. Otherwise, try to load the identity file
1721 * of the certificate issuer. If the issuer file is not found,
1722 * try the host file. If nothing found, declare a cryptobust.
1723 * Note we can't get here unless the trusted certificate has
1724 * been found and the CRYPTO_FLAG_VALID bit is set, so the
1725 * certificate issuer is valid.
1727 if (peer
->ident_pkey
!= NULL
)
1728 EVP_PKEY_free(peer
->ident_pkey
);
1729 if (peer
->crypto
& CRYPTO_FLAG_GQ
) {
1730 snprintf(filename
, MAXFILENAME
, "ntpkey_gq_%s",
1732 peer
->ident_pkey
= crypto_key(filename
, &peer
->fstamp
);
1733 if (peer
->ident_pkey
!= NULL
)
1736 snprintf(filename
, MAXFILENAME
, "ntpkey_gq_%s",
1738 peer
->ident_pkey
= crypto_key(filename
, &peer
->fstamp
);
1739 if (peer
->ident_pkey
!= NULL
)
1742 if (peer
->crypto
& CRYPTO_FLAG_IFF
) {
1743 snprintf(filename
, MAXFILENAME
, "ntpkey_iff_%s",
1745 peer
->ident_pkey
= crypto_key(filename
, &peer
->fstamp
);
1746 if (peer
->ident_pkey
!= NULL
)
1747 return (CRYPTO_IFF
);
1749 snprintf(filename
, MAXFILENAME
, "ntpkey_iff_%s",
1751 peer
->ident_pkey
= crypto_key(filename
, &peer
->fstamp
);
1752 if (peer
->ident_pkey
!= NULL
)
1753 return (CRYPTO_IFF
);
1755 if (peer
->crypto
& CRYPTO_FLAG_MV
) {
1756 snprintf(filename
, MAXFILENAME
, "ntpkey_mv_%s",
1758 peer
->ident_pkey
= crypto_key(filename
, &peer
->fstamp
);
1759 if (peer
->ident_pkey
!= NULL
)
1762 snprintf(filename
, MAXFILENAME
, "ntpkey_mv_%s",
1764 peer
->ident_pkey
= crypto_key(filename
, &peer
->fstamp
);
1765 if (peer
->ident_pkey
!= NULL
)
1770 * No compatible identity scheme is available. Life is hard.
1773 "crypto_ident: no compatible identity scheme found");
1779 * crypto_args - construct extension field from arguments
1781 * This routine creates an extension field with current timestamps and
1782 * specified opcode, association ID and optional string. Note that the
1783 * extension field is created here, but freed after the crypto_xmit()
1784 * call in the protocol module.
1786 * Returns extension field pointer (no errors).
1790 struct peer
*peer
, /* peer structure pointer */
1791 u_int opcode
, /* operation code */
1792 char *str
/* argument string */
1795 tstamp_t tstamp
; /* NTP timestamp */
1796 struct exten
*ep
; /* extension field pointer */
1797 u_int len
; /* extension field length */
1799 tstamp
= crypto_time();
1800 len
= sizeof(struct exten
);
1808 ep
->opcode
= htonl(opcode
+ len
);
1811 * If a response, send our ID; if a request, send the
1814 if (opcode
& CRYPTO_RESP
)
1815 ep
->associd
= htonl(peer
->associd
);
1817 ep
->associd
= htonl(peer
->assoc
);
1818 ep
->tstamp
= htonl(tstamp
);
1819 ep
->fstamp
= hostval
.tstamp
;
1822 ep
->vallen
= htonl(strlen(str
));
1823 memcpy((char *)ep
->pkt
, str
, strlen(str
));
1825 ep
->pkt
[0] = peer
->associd
;
1832 * crypto_send - construct extension field from value components
1834 * Returns extension field length. Note: it is not polite to send a
1835 * nonempty signature with zero timestamp or a nonzero timestamp with
1836 * empty signature, but these rules are not enforced here.
1840 struct exten
*ep
, /* extension field pointer */
1841 struct value
*vp
/* value pointer */
1848 * Copy data. If the data field is empty or zero length, encode
1849 * an empty value with length zero.
1851 ep
->tstamp
= vp
->tstamp
;
1852 ep
->fstamp
= vp
->fstamp
;
1853 ep
->vallen
= vp
->vallen
;
1855 temp32
= ntohl(vp
->vallen
);
1856 if (temp32
> 0 && vp
->ptr
!= NULL
)
1857 memcpy(ep
->pkt
, vp
->ptr
, temp32
);
1860 * Copy signature. If the signature field is empty or zero
1861 * length, encode an empty signature with length zero.
1863 i
= (temp32
+ 3) / 4;
1865 ep
->pkt
[i
++] = vp
->siglen
;
1866 temp32
= ntohl(vp
->siglen
);
1867 if (temp32
> 0 && vp
->sig
!= NULL
)
1868 memcpy(&ep
->pkt
[i
], vp
->sig
, temp32
);
1875 * crypto_update - compute new public value and sign extension fields
1877 * This routine runs periodically, like once a day, and when something
1878 * changes. It updates the timestamps on three value structures and one
1879 * value structure list, then signs all the structures:
1881 * hostval host name (not signed)
1883 * cinfo certificate info/value list
1884 * tai_leap leapseconds file
1886 * Filestamps are proventicated data, so this routine is run only when
1887 * the host has been synchronized to a proventicated source. Thus, the
1888 * timestamp is proventicated, too, and can be used to deflect
1889 * clogging attacks and even cook breakfast.
1891 * Returns void (no errors)
1896 EVP_MD_CTX ctx
; /* message digest context */
1897 struct cert_info
*cp
, *cpn
; /* certificate info/value */
1898 char statstr
[NTP_MAXSTRLEN
]; /* statistics for filegen */
1899 tstamp_t tstamp
; /* NTP timestamp */
1902 if ((tstamp
= crypto_time()) == 0)
1905 hostval
.tstamp
= htonl(tstamp
);
1908 * Sign public key and timestamps. The filestamp is derived from
1909 * the host key file extension from wherever the file was
1912 if (pubkey
.vallen
!= 0) {
1913 pubkey
.tstamp
= hostval
.tstamp
;
1915 if (pubkey
.sig
== NULL
)
1916 pubkey
.sig
= emalloc(sign_siglen
);
1917 EVP_SignInit(&ctx
, sign_digest
);
1918 EVP_SignUpdate(&ctx
, (u_char
*)&pubkey
, 12);
1919 EVP_SignUpdate(&ctx
, pubkey
.ptr
, ntohl(pubkey
.vallen
));
1920 if (EVP_SignFinal(&ctx
, pubkey
.sig
, &len
, sign_pkey
))
1921 pubkey
.siglen
= htonl(len
);
1925 * Sign certificates and timestamps. The filestamp is derived
1926 * from the certificate file extension from wherever the file
1927 * was generated. Note we do not throw expired certificates
1928 * away; they may have signed younger ones.
1930 for (cp
= cinfo
; cp
!= NULL
; cp
= cpn
) {
1932 cp
->cert
.tstamp
= hostval
.tstamp
;
1933 cp
->cert
.siglen
= 0;
1934 if (cp
->cert
.sig
== NULL
)
1935 cp
->cert
.sig
= emalloc(sign_siglen
);
1936 EVP_SignInit(&ctx
, sign_digest
);
1937 EVP_SignUpdate(&ctx
, (u_char
*)&cp
->cert
, 12);
1938 EVP_SignUpdate(&ctx
, cp
->cert
.ptr
,
1939 ntohl(cp
->cert
.vallen
));
1940 if (EVP_SignFinal(&ctx
, cp
->cert
.sig
, &len
, sign_pkey
))
1941 cp
->cert
.siglen
= htonl(len
);
1945 * Sign leapseconds table and timestamps. The filestamp is
1946 * derived from the leapsecond file extension from wherever the
1947 * file was generated.
1949 if (tai_leap
.vallen
!= 0) {
1950 tai_leap
.tstamp
= hostval
.tstamp
;
1951 tai_leap
.siglen
= 0;
1952 if (tai_leap
.sig
== NULL
)
1953 tai_leap
.sig
= emalloc(sign_siglen
);
1954 EVP_SignInit(&ctx
, sign_digest
);
1955 EVP_SignUpdate(&ctx
, (u_char
*)&tai_leap
, 12);
1956 EVP_SignUpdate(&ctx
, tai_leap
.ptr
,
1957 ntohl(tai_leap
.vallen
));
1958 if (EVP_SignFinal(&ctx
, tai_leap
.sig
, &len
, sign_pkey
))
1959 tai_leap
.siglen
= htonl(len
);
1961 snprintf(statstr
, NTP_MAXSTRLEN
,
1962 "update ts %u", ntohl(hostval
.tstamp
));
1963 record_crypto_stats(NULL
, statstr
);
1966 printf("crypto_update: %s\n", statstr
);
1972 * value_free - free value structure components.
1974 * Returns void (no errors)
1978 struct value
*vp
/* value structure */
1981 if (vp
->ptr
!= NULL
)
1983 if (vp
->sig
!= NULL
)
1985 memset(vp
, 0, sizeof(struct value
));
1990 * crypto_time - returns current NTP time in seconds.
1995 l_fp tstamp
; /* NTP time */ L_CLR(&tstamp
);
1998 if (sys_leap
!= LEAP_NOTINSYNC
)
1999 get_systime(&tstamp
);
2000 return (tstamp
.l_ui
);
2005 * asn2ntp - convert ASN1_TIME time structure to NTP time in seconds.
2009 ASN1_TIME
*asn1time
/* pointer to ASN1_TIME structure */
2012 char *v
; /* pointer to ASN1_TIME string */
2013 struct tm tm
; /* used to convert to NTP time */
2016 * Extract time string YYMMDDHHMMSSZ from ASN1 time structure.
2017 * Note that the YY, MM, DD fields start with one, the HH, MM,
2018 * SS fiels start with zero and the Z character should be 'Z'
2019 * for UTC. Also note that years less than 50 map to years
2020 * greater than 100. Dontcha love ASN.1? Better than MIL-188.
2022 if (asn1time
->length
> 13)
2023 return ((u_long
)(~0)); /* We can't use -1 here. It's invalid */
2025 v
= (char *)asn1time
->data
;
2026 tm
.tm_year
= (v
[0] - '0') * 10 + v
[1] - '0';
2027 if (tm
.tm_year
< 50)
2029 tm
.tm_mon
= (v
[2] - '0') * 10 + v
[3] - '0' - 1;
2030 tm
.tm_mday
= (v
[4] - '0') * 10 + v
[5] - '0';
2031 tm
.tm_hour
= (v
[6] - '0') * 10 + v
[7] - '0';
2032 tm
.tm_min
= (v
[8] - '0') * 10 + v
[9] - '0';
2033 tm
.tm_sec
= (v
[10] - '0') * 10 + v
[11] - '0';
2037 return (timegm(&tm
) + JAN_1970
);
2042 * bigdig() - compute a BIGNUM MD5 hash of a BIGNUM number.
2046 BIGNUM
*bn
, /* BIGNUM * from */
2047 BIGNUM
*bk
/* BIGNUM * to */
2050 EVP_MD_CTX ctx
; /* message digest context */
2051 u_char dgst
[EVP_MAX_MD_SIZE
]; /* message digest */
2052 u_char
*ptr
; /* a BIGNUM as binary string */
2055 len
= BN_num_bytes(bn
);
2058 EVP_DigestInit(&ctx
, EVP_md5());
2059 EVP_DigestUpdate(&ctx
, ptr
, len
);
2060 EVP_DigestFinal(&ctx
, dgst
, &len
);
2061 BN_bin2bn(dgst
, len
, bk
);
2063 /* XXX MEMLEAK? free ptr? */
2070 ***********************************************************************
2072 * The following routines implement the Schnorr (IFF) identity scheme *
2074 ***********************************************************************
2076 * The Schnorr (IFF) identity scheme is intended for use when
2077 * the ntp-genkeys program does not generate the certificates used in
2078 * the protocol and the group key cannot be conveyed in the certificate
2079 * itself. For this purpose, new generations of IFF values must be
2080 * securely transmitted to all members of the group before use. The
2081 * scheme is self contained and independent of new generations of host
2082 * keys, sign keys and certificates.
2084 * The IFF identity scheme is based on DSA cryptography and algorithms
2085 * described in Stinson p. 285. The IFF values hide in a DSA cuckoo
2086 * structure, but only the primes and generator are used. The p is a
2087 * 512-bit prime, q a 160-bit prime that divides p - 1 and is a qth root
2088 * of 1 mod p; that is, g^q = 1 mod p. The TA rolls primvate random
2089 * group key b disguised as a DSA structure member, then computes public
2090 * key g^(q - b). These values are shared only among group members and
2091 * never revealed in messages. Alice challenges Bob to confirm identity
2092 * using the protocol described below.
2096 * The scheme goes like this. Both Alice and Bob have the public primes
2097 * p, q and generator g. The TA gives private key b to Bob and public
2098 * key v = g^(q - a) mod p to Alice.
2100 * Alice rolls new random challenge r and sends to Bob in the IFF
2101 * request message. Bob rolls new random k, then computes y = k + b r
2102 * mod q and x = g^k mod p and sends (y, hash(x)) to Alice in the
2103 * response message. Besides making the response shorter, the hash makes
2104 * it effectivey impossible for an intruder to solve for b by observing
2105 * a number of these messages.
2107 * Alice receives the response and computes g^y v^r mod p. After a bit
2108 * of algebra, this simplifies to g^k. If the hash of this result
2109 * matches hash(x), Alice knows that Bob has the group key b. The signed
2110 * response binds this knowledge to Bob's private key and the public key
2111 * previously received in his certificate.
2113 * crypto_alice - construct Alice's challenge in IFF scheme
2117 * XEVNT_PUB bad or missing public key
2118 * XEVNT_ID bad or missing group key
2122 struct peer
*peer
, /* peer pointer */
2123 struct value
*vp
/* value pointer */
2126 DSA
*dsa
; /* IFF parameters */
2127 BN_CTX
*bctx
; /* BIGNUM context */
2128 EVP_MD_CTX ctx
; /* signature context */
2133 * The identity parameters must have correct format and content.
2135 if (peer
->ident_pkey
== NULL
)
2138 if ((dsa
= peer
->ident_pkey
->pkey
.dsa
) == NULL
) {
2139 msyslog(LOG_INFO
, "crypto_alice: defective key");
2144 * Roll new random r (0 < r < q). The OpenSSL library has a bug
2145 * omitting BN_rand_range, so we have to do it the hard way.
2147 bctx
= BN_CTX_new();
2148 len
= BN_num_bytes(dsa
->q
);
2149 if (peer
->iffval
!= NULL
)
2150 BN_free(peer
->iffval
);
2151 peer
->iffval
= BN_new();
2152 BN_rand(peer
->iffval
, len
* 8, -1, 1); /* r */
2153 BN_mod(peer
->iffval
, peer
->iffval
, dsa
->q
, bctx
);
2157 * Sign and send to Bob. The filestamp is from the local file.
2159 tstamp
= crypto_time();
2160 memset(vp
, 0, sizeof(struct value
));
2161 vp
->tstamp
= htonl(tstamp
);
2162 vp
->fstamp
= htonl(peer
->fstamp
);
2163 vp
->vallen
= htonl(len
);
2164 vp
->ptr
= emalloc(len
);
2165 BN_bn2bin(peer
->iffval
, vp
->ptr
);
2170 if (tstamp
< cinfo
->first
|| tstamp
> cinfo
->last
)
2173 vp
->sig
= emalloc(sign_siglen
);
2174 EVP_SignInit(&ctx
, sign_digest
);
2175 EVP_SignUpdate(&ctx
, (u_char
*)&vp
->tstamp
, 12);
2176 EVP_SignUpdate(&ctx
, vp
->ptr
, len
);
2177 if (EVP_SignFinal(&ctx
, vp
->sig
, &len
, sign_pkey
))
2178 vp
->siglen
= htonl(len
);
2184 * crypto_bob - construct Bob's response to Alice's challenge
2188 * XEVNT_ID bad or missing group key
2189 * XEVNT_ERR protocol error
2190 * XEVNT_PER host expired certificate
2194 struct exten
*ep
, /* extension pointer */
2195 struct value
*vp
/* value pointer */
2198 DSA
*dsa
; /* IFF parameters */
2199 DSA_SIG
*sdsa
; /* DSA signature context fake */
2200 BN_CTX
*bctx
; /* BIGNUM context */
2201 EVP_MD_CTX ctx
; /* signature context */
2202 tstamp_t tstamp
; /* NTP timestamp */
2203 BIGNUM
*bn
, *bk
, *r
;
2208 * If the IFF parameters are not valid, something awful
2209 * happened or we are being tormented.
2211 if (iffpar_pkey
== NULL
) {
2212 msyslog(LOG_INFO
, "crypto_bob: scheme unavailable");
2215 dsa
= iffpar_pkey
->pkey
.dsa
;
2218 * Extract r from the challenge.
2220 len
= ntohl(ep
->vallen
);
2221 if ((r
= BN_bin2bn((u_char
*)ep
->pkt
, len
, NULL
)) == NULL
) {
2222 msyslog(LOG_ERR
, "crypto_bob %s\n",
2223 ERR_error_string(ERR_get_error(), NULL
));
2228 * Bob rolls random k (0 < k < q), computes y = k + b r mod q
2229 * and x = g^k mod p, then sends (y, hash(x)) to Alice.
2231 bctx
= BN_CTX_new(); bk
= BN_new(); bn
= BN_new();
2232 sdsa
= DSA_SIG_new();
2233 BN_rand(bk
, len
* 8, -1, 1); /* k */
2234 BN_mod_mul(bn
, dsa
->priv_key
, r
, dsa
->q
, bctx
); /* b r mod q */
2236 BN_mod(bn
, bn
, dsa
->q
, bctx
); /* k + b r mod q */
2237 sdsa
->r
= BN_dup(bn
);
2238 BN_mod_exp(bk
, dsa
->g
, bk
, dsa
->p
, bctx
); /* g^k mod p */
2240 sdsa
->s
= BN_dup(bk
);
2242 BN_free(r
); BN_free(bn
); BN_free(bk
);
2245 * Encode the values in ASN.1 and sign.
2247 tstamp
= crypto_time();
2248 memset(vp
, 0, sizeof(struct value
));
2249 vp
->tstamp
= htonl(tstamp
);
2250 vp
->fstamp
= htonl(if_fstamp
);
2251 len
= i2d_DSA_SIG(sdsa
, NULL
);
2253 msyslog(LOG_ERR
, "crypto_bob %s\n",
2254 ERR_error_string(ERR_get_error(), NULL
));
2258 vp
->vallen
= htonl(len
);
2261 i2d_DSA_SIG(sdsa
, &ptr
);
2267 if (tstamp
< cinfo
->first
|| tstamp
> cinfo
->last
)
2270 vp
->sig
= emalloc(sign_siglen
);
2271 EVP_SignInit(&ctx
, sign_digest
);
2272 EVP_SignUpdate(&ctx
, (u_char
*)&vp
->tstamp
, 12);
2273 EVP_SignUpdate(&ctx
, vp
->ptr
, len
);
2274 if (EVP_SignFinal(&ctx
, vp
->sig
, &len
, sign_pkey
))
2275 vp
->siglen
= htonl(len
);
2281 * crypto_iff - verify Bob's response to Alice's challenge
2285 * XEVNT_PUB bad or missing public key
2286 * XEVNT_ID bad or missing group key
2287 * XEVNT_FSP bad filestamp
2291 struct exten
*ep
, /* extension pointer */
2292 struct peer
*peer
/* peer structure pointer */
2295 DSA
*dsa
; /* IFF parameters */
2296 BN_CTX
*bctx
; /* BIGNUM context */
2297 DSA_SIG
*sdsa
; /* DSA parameters */
2304 * If the IFF parameters are not valid or no challenge was sent,
2305 * something awful happened or we are being tormented.
2307 if (peer
->ident_pkey
== NULL
) {
2308 msyslog(LOG_INFO
, "crypto_iff: scheme unavailable");
2311 if (ntohl(ep
->fstamp
) != peer
->fstamp
) {
2312 msyslog(LOG_INFO
, "crypto_iff: invalid filestamp %u",
2316 if ((dsa
= peer
->ident_pkey
->pkey
.dsa
) == NULL
) {
2317 msyslog(LOG_INFO
, "crypto_iff: defective key");
2320 if (peer
->iffval
== NULL
) {
2321 msyslog(LOG_INFO
, "crypto_iff: missing challenge");
2326 * Extract the k + b r and g^k values from the response.
2328 bctx
= BN_CTX_new(); bk
= BN_new(); bn
= BN_new();
2329 len
= ntohl(ep
->vallen
);
2330 ptr
= (const u_char
*)ep
->pkt
;
2331 if ((sdsa
= d2i_DSA_SIG(NULL
, &ptr
, len
)) == NULL
) {
2332 msyslog(LOG_ERR
, "crypto_iff %s\n",
2333 ERR_error_string(ERR_get_error(), NULL
));
2338 * Compute g^(k + b r) g^(q - b)r mod p.
2340 BN_mod_exp(bn
, dsa
->pub_key
, peer
->iffval
, dsa
->p
, bctx
);
2341 BN_mod_exp(bk
, dsa
->g
, sdsa
->r
, dsa
->p
, bctx
);
2342 BN_mod_mul(bn
, bn
, bk
, dsa
->p
, bctx
);
2345 * Verify the hash of the result matches hash(x).
2348 temp
= BN_cmp(bn
, sdsa
->s
);
2349 BN_free(bn
); BN_free(bk
); BN_CTX_free(bctx
);
2350 BN_free(peer
->iffval
);
2351 peer
->iffval
= NULL
;
2362 ***********************************************************************
2364 * The following routines implement the Guillou-Quisquater (GQ) *
2367 ***********************************************************************
2369 * The Guillou-Quisquater (GQ) identity scheme is intended for use when
2370 * the ntp-genkeys program generates the certificates used in the
2371 * protocol and the group key can be conveyed in a certificate extension
2372 * field. The scheme is self contained and independent of new
2373 * generations of host keys, sign keys and certificates.
2375 * The GQ identity scheme is based on RSA cryptography and algorithms
2376 * described in Stinson p. 300 (with errors). The GQ values hide in a
2377 * RSA cuckoo structure, but only the modulus is used. The 512-bit
2378 * public modulus is n = p q, where p and q are secret large primes. The
2379 * TA rolls random group key b disguised as a RSA structure member.
2380 * Except for the public key, these values are shared only among group
2381 * members and never revealed in messages.
2383 * When rolling new certificates, Bob recomputes the private and
2384 * public keys. The private key u is a random roll, while the public key
2385 * is the inverse obscured by the group key v = (u^-1)^b. These values
2386 * replace the private and public keys normally generated by the RSA
2387 * scheme. Alice challenges Bob to confirm identity using the protocol
2392 * The scheme goes like this. Both Alice and Bob have the same modulus n
2393 * and some random b as the group key. These values are computed and
2394 * distributed in advance via secret means, although only the group key
2395 * b is truly secret. Each has a private random private key u and public
2396 * key (u^-1)^b, although not necessarily the same ones. Bob and Alice
2397 * can regenerate the key pair from time to time without affecting
2398 * operations. The public key is conveyed on the certificate in an
2399 * extension field; the private key is never revealed.
2401 * Alice rolls new random challenge r and sends to Bob in the GQ
2402 * request message. Bob rolls new random k, then computes y = k u^r mod
2403 * n and x = k^b mod n and sends (y, hash(x)) to Alice in the response
2404 * message. Besides making the response shorter, the hash makes it
2405 * effectivey impossible for an intruder to solve for b by observing
2406 * a number of these messages.
2408 * Alice receives the response and computes y^b v^r mod n. After a bit
2409 * of algebra, this simplifies to k^b. If the hash of this result
2410 * matches hash(x), Alice knows that Bob has the group key b. The signed
2411 * response binds this knowledge to Bob's private key and the public key
2412 * previously received in his certificate.
2414 * crypto_alice2 - construct Alice's challenge in GQ scheme
2418 * XEVNT_PUB bad or missing public key
2419 * XEVNT_ID bad or missing group key
2420 * XEVNT_PER host certificate expired
2424 struct peer
*peer
, /* peer pointer */
2425 struct value
*vp
/* value pointer */
2428 RSA
*rsa
; /* GQ parameters */
2429 BN_CTX
*bctx
; /* BIGNUM context */
2430 EVP_MD_CTX ctx
; /* signature context */
2435 * The identity parameters must have correct format and content.
2437 if (peer
->ident_pkey
== NULL
)
2440 if ((rsa
= peer
->ident_pkey
->pkey
.rsa
) == NULL
) {
2441 msyslog(LOG_INFO
, "crypto_alice2: defective key");
2446 * Roll new random r (0 < r < n). The OpenSSL library has a bug
2447 * omitting BN_rand_range, so we have to do it the hard way.
2449 bctx
= BN_CTX_new();
2450 len
= BN_num_bytes(rsa
->n
);
2451 if (peer
->iffval
!= NULL
)
2452 BN_free(peer
->iffval
);
2453 peer
->iffval
= BN_new();
2454 BN_rand(peer
->iffval
, len
* 8, -1, 1); /* r mod n */
2455 BN_mod(peer
->iffval
, peer
->iffval
, rsa
->n
, bctx
);
2459 * Sign and send to Bob. The filestamp is from the local file.
2461 tstamp
= crypto_time();
2462 memset(vp
, 0, sizeof(struct value
));
2463 vp
->tstamp
= htonl(tstamp
);
2464 vp
->fstamp
= htonl(peer
->fstamp
);
2465 vp
->vallen
= htonl(len
);
2466 vp
->ptr
= emalloc(len
);
2467 BN_bn2bin(peer
->iffval
, vp
->ptr
);
2472 if (tstamp
< cinfo
->first
|| tstamp
> cinfo
->last
)
2475 vp
->sig
= emalloc(sign_siglen
);
2476 EVP_SignInit(&ctx
, sign_digest
);
2477 EVP_SignUpdate(&ctx
, (u_char
*)&vp
->tstamp
, 12);
2478 EVP_SignUpdate(&ctx
, vp
->ptr
, len
);
2479 if (EVP_SignFinal(&ctx
, vp
->sig
, &len
, sign_pkey
))
2480 vp
->siglen
= htonl(len
);
2486 * crypto_bob2 - construct Bob's response to Alice's challenge
2490 * XEVNT_ID bad or missing group key
2491 * XEVNT_ERR protocol error
2492 * XEVNT_PER host certificate expired
2496 struct exten
*ep
, /* extension pointer */
2497 struct value
*vp
/* value pointer */
2500 RSA
*rsa
; /* GQ parameters */
2501 DSA_SIG
*sdsa
; /* DSA parameters */
2502 BN_CTX
*bctx
; /* BIGNUM context */
2503 EVP_MD_CTX ctx
; /* signature context */
2504 tstamp_t tstamp
; /* NTP timestamp */
2505 BIGNUM
*r
, *k
, *g
, *y
;
2510 * If the GQ parameters are not valid, something awful
2511 * happened or we are being tormented.
2513 if (gqpar_pkey
== NULL
) {
2514 msyslog(LOG_INFO
, "crypto_bob2: scheme unavailable");
2517 rsa
= gqpar_pkey
->pkey
.rsa
;
2520 * Extract r from the challenge.
2522 len
= ntohl(ep
->vallen
);
2523 if ((r
= BN_bin2bn((u_char
*)ep
->pkt
, len
, NULL
)) == NULL
) {
2524 msyslog(LOG_ERR
, "crypto_bob2 %s\n",
2525 ERR_error_string(ERR_get_error(), NULL
));
2530 * Bob rolls random k (0 < k < n), computes y = k u^r mod n and
2531 * x = k^b mod n, then sends (y, hash(x)) to Alice.
2533 bctx
= BN_CTX_new(); k
= BN_new(); g
= BN_new(); y
= BN_new();
2534 sdsa
= DSA_SIG_new();
2535 BN_rand(k
, len
* 8, -1, 1); /* k */
2536 BN_mod(k
, k
, rsa
->n
, bctx
);
2537 BN_mod_exp(y
, rsa
->p
, r
, rsa
->n
, bctx
); /* u^r mod n */
2538 BN_mod_mul(y
, k
, y
, rsa
->n
, bctx
); /* k u^r mod n */
2539 sdsa
->r
= BN_dup(y
);
2540 BN_mod_exp(g
, k
, rsa
->e
, rsa
->n
, bctx
); /* k^b mod n */
2542 sdsa
->s
= BN_dup(g
);
2544 BN_free(r
); BN_free(k
); BN_free(g
); BN_free(y
);
2547 * Encode the values in ASN.1 and sign.
2549 tstamp
= crypto_time();
2550 memset(vp
, 0, sizeof(struct value
));
2551 vp
->tstamp
= htonl(tstamp
);
2552 vp
->fstamp
= htonl(gq_fstamp
);
2553 len
= i2d_DSA_SIG(sdsa
, NULL
);
2555 msyslog(LOG_ERR
, "crypto_bob2 %s\n",
2556 ERR_error_string(ERR_get_error(), NULL
));
2560 vp
->vallen
= htonl(len
);
2563 i2d_DSA_SIG(sdsa
, &ptr
);
2569 if (tstamp
< cinfo
->first
|| tstamp
> cinfo
->last
)
2572 vp
->sig
= emalloc(sign_siglen
);
2573 EVP_SignInit(&ctx
, sign_digest
);
2574 EVP_SignUpdate(&ctx
, (u_char
*)&vp
->tstamp
, 12);
2575 EVP_SignUpdate(&ctx
, vp
->ptr
, len
);
2576 if (EVP_SignFinal(&ctx
, vp
->sig
, &len
, sign_pkey
))
2577 vp
->siglen
= htonl(len
);
2583 * crypto_gq - verify Bob's response to Alice's challenge
2587 * XEVNT_PUB bad or missing public key
2588 * XEVNT_ID bad or missing group keys
2589 * XEVNT_ERR protocol error
2590 * XEVNT_FSP bad filestamp
2594 struct exten
*ep
, /* extension pointer */
2595 struct peer
*peer
/* peer structure pointer */
2598 RSA
*rsa
; /* GQ parameters */
2599 BN_CTX
*bctx
; /* BIGNUM context */
2600 DSA_SIG
*sdsa
; /* RSA signature context fake */
2607 * If the GQ parameters are not valid or no challenge was sent,
2608 * something awful happened or we are being tormented.
2610 if (peer
->ident_pkey
== NULL
) {
2611 msyslog(LOG_INFO
, "crypto_gq: scheme unavailable");
2614 if (ntohl(ep
->fstamp
) != peer
->fstamp
) {
2615 msyslog(LOG_INFO
, "crypto_gq: invalid filestamp %u",
2619 if ((rsa
= peer
->ident_pkey
->pkey
.rsa
) == NULL
) {
2620 msyslog(LOG_INFO
, "crypto_gq: defective key");
2623 if (peer
->iffval
== NULL
) {
2624 msyslog(LOG_INFO
, "crypto_gq: missing challenge");
2629 * Extract the y = k u^r and hash(x = k^b) values from the
2632 bctx
= BN_CTX_new(); y
= BN_new(); v
= BN_new();
2633 len
= ntohl(ep
->vallen
);
2634 ptr
= (const u_char
*)ep
->pkt
;
2635 if ((sdsa
= d2i_DSA_SIG(NULL
, &ptr
, len
)) == NULL
) {
2636 msyslog(LOG_ERR
, "crypto_gq %s\n",
2637 ERR_error_string(ERR_get_error(), NULL
));
2642 * Compute v^r y^b mod n.
2644 BN_mod_exp(v
, peer
->grpkey
, peer
->iffval
, rsa
->n
, bctx
);
2646 BN_mod_exp(y
, sdsa
->r
, rsa
->e
, rsa
->n
, bctx
); /* y^b mod n */
2647 BN_mod_mul(y
, v
, y
, rsa
->n
, bctx
); /* v^r y^b mod n */
2650 * Verify the hash of the result matches hash(x).
2653 temp
= BN_cmp(y
, sdsa
->s
);
2654 BN_CTX_free(bctx
); BN_free(y
); BN_free(v
);
2655 BN_free(peer
->iffval
);
2656 peer
->iffval
= NULL
;
2667 ***********************************************************************
2669 * The following routines implement the Mu-Varadharajan (MV) identity *
2672 ***********************************************************************
2675 * The Mu-Varadharajan (MV) cryptosystem was originally intended when
2676 * servers broadcast messages to clients, but clients never send
2677 * messages to servers. There is one encryption key for the server and a
2678 * separate decryption key for each client. It operated something like a
2679 * pay-per-view satellite broadcasting system where the session key is
2680 * encrypted by the broadcaster and the decryption keys are held in a
2681 * tamperproof set-top box.
2683 * The MV parameters and private encryption key hide in a DSA cuckoo
2684 * structure which uses the same parameters, but generated in a
2685 * different way. The values are used in an encryption scheme similar to
2686 * El Gamal cryptography and a polynomial formed from the expansion of
2687 * product terms (x - x[j]), as described in Mu, Y., and V.
2688 * Varadharajan: Robust and Secure Broadcasting, Proc. Indocrypt 2001,
2689 * 223-231. The paper has significant errors and serious omissions.
2691 * Let q be the product of n distinct primes s'[j] (j = 1...n), where
2692 * each s'[j] has m significant bits. Let p be a prime p = 2 * q + 1, so
2693 * that q and each s'[j] divide p - 1 and p has M = n * m + 1
2694 * significant bits. The elements x mod q of Zq with the elements 2 and
2695 * the primes removed form a field Zq* valid for polynomial arithetic.
2696 * Let g be a generator of Zp; that is, gcd(g, p - 1) = 1 and g^q = 1
2697 * mod p. We expect M to be in the 500-bit range and n relatively small,
2698 * like 25, so the likelihood of a randomly generated element of x mod q
2699 * of Zq colliding with a factor of p - 1 is very small and can be
2700 * avoided. Associated with each s'[j] is an element s[j] such that s[j]
2701 * s'[j] = s'[j] mod q. We find s[j] as the quotient (q + s'[j]) /
2702 * s'[j]. These are the parameters of the scheme and they are expensive
2705 * We set up an instance of the scheme as follows. A set of random
2706 * values x[j] mod q (j = 1...n), are generated as the zeros of a
2707 * polynomial of order n. The product terms (x - x[j]) are expanded to
2708 * form coefficients a[i] mod q (i = 0...n) in powers of x. These are
2709 * used as exponents of the generator g mod p to generate the private
2710 * encryption key A. The pair (gbar, ghat) of public server keys and the
2711 * pairs (xbar[j], xhat[j]) (j = 1...n) of private client keys are used
2712 * to construct the decryption keys. The devil is in the details.
2714 * The distinguishing characteristic of this scheme is the capability to
2715 * revoke keys. Included in the calculation of E, gbar and ghat is the
2716 * product s = prod(s'[j]) (j = 1...n) above. If the factor s'[j] is
2717 * subsequently removed from the product and E, gbar and ghat
2718 * recomputed, the jth client will no longer be able to compute E^-1 and
2719 * thus unable to decrypt the block.
2723 * The scheme goes like this. Bob has the server values (p, A, q, gbar,
2724 * ghat) and Alice the client values (p, xbar, xhat).
2726 * Alice rolls new random challenge r (0 < r < p) and sends to Bob in
2727 * the MV request message. Bob rolls new random k (0 < k < q), encrypts
2728 * y = A^k mod p (a permutation) and sends (hash(y), gbar^k, ghat^k) to
2731 * Alice receives the response and computes the decryption key (the
2732 * inverse permutation) from previously obtained (xbar, xhat) and
2733 * (gbar^k, ghat^k) in the message. She computes the inverse, which is
2734 * unique by reasons explained in the ntp-keygen.c program sources. If
2735 * the hash of this result matches hash(y), Alice knows that Bob has the
2736 * group key b. The signed response binds this knowledge to Bob's
2737 * private key and the public key previously received in his
2740 * crypto_alice3 - construct Alice's challenge in MV scheme
2744 * XEVNT_PUB bad or missing public key
2745 * XEVNT_ID bad or missing group key
2746 * XEVNT_PER host certificate expired
2750 struct peer
*peer
, /* peer pointer */
2751 struct value
*vp
/* value pointer */
2754 DSA
*dsa
; /* MV parameters */
2755 BN_CTX
*bctx
; /* BIGNUM context */
2756 EVP_MD_CTX ctx
; /* signature context */
2761 * The identity parameters must have correct format and content.
2763 if (peer
->ident_pkey
== NULL
)
2766 if ((dsa
= peer
->ident_pkey
->pkey
.dsa
) == NULL
) {
2767 msyslog(LOG_INFO
, "crypto_alice3: defective key");
2772 * Roll new random r (0 < r < q). The OpenSSL library has a bug
2773 * omitting BN_rand_range, so we have to do it the hard way.
2775 bctx
= BN_CTX_new();
2776 len
= BN_num_bytes(dsa
->p
);
2777 if (peer
->iffval
!= NULL
)
2778 BN_free(peer
->iffval
);
2779 peer
->iffval
= BN_new();
2780 BN_rand(peer
->iffval
, len
* 8, -1, 1); /* r */
2781 BN_mod(peer
->iffval
, peer
->iffval
, dsa
->p
, bctx
);
2785 * Sign and send to Bob. The filestamp is from the local file.
2787 tstamp
= crypto_time();
2788 memset(vp
, 0, sizeof(struct value
));
2789 vp
->tstamp
= htonl(tstamp
);
2790 vp
->fstamp
= htonl(peer
->fstamp
);
2791 vp
->vallen
= htonl(len
);
2792 vp
->ptr
= emalloc(len
);
2793 BN_bn2bin(peer
->iffval
, vp
->ptr
);
2798 if (tstamp
< cinfo
->first
|| tstamp
> cinfo
->last
)
2801 vp
->sig
= emalloc(sign_siglen
);
2802 EVP_SignInit(&ctx
, sign_digest
);
2803 EVP_SignUpdate(&ctx
, (u_char
*)&vp
->tstamp
, 12);
2804 EVP_SignUpdate(&ctx
, vp
->ptr
, len
);
2805 if (EVP_SignFinal(&ctx
, vp
->sig
, &len
, sign_pkey
))
2806 vp
->siglen
= htonl(len
);
2812 * crypto_bob3 - construct Bob's response to Alice's challenge
2816 * XEVNT_ERR protocol error
2817 * XEVNT_PER host certificate expired
2821 struct exten
*ep
, /* extension pointer */
2822 struct value
*vp
/* value pointer */
2825 DSA
*dsa
; /* MV parameters */
2826 DSA
*sdsa
; /* DSA signature context fake */
2827 BN_CTX
*bctx
; /* BIGNUM context */
2828 EVP_MD_CTX ctx
; /* signature context */
2829 tstamp_t tstamp
; /* NTP timestamp */
2835 * If the MV parameters are not valid, something awful
2836 * happened or we are being tormented.
2838 if (mvpar_pkey
== NULL
) {
2839 msyslog(LOG_INFO
, "crypto_bob3: scheme unavailable");
2842 dsa
= mvpar_pkey
->pkey
.dsa
;
2845 * Extract r from the challenge.
2847 len
= ntohl(ep
->vallen
);
2848 if ((r
= BN_bin2bn((u_char
*)ep
->pkt
, len
, NULL
)) == NULL
) {
2849 msyslog(LOG_ERR
, "crypto_bob3 %s\n",
2850 ERR_error_string(ERR_get_error(), NULL
));
2855 * Bob rolls random k (0 < k < q), making sure it is not a
2856 * factor of q. He then computes y = A^k r and sends (hash(y),
2857 * gbar^k, ghat^k) to Alice.
2859 bctx
= BN_CTX_new(); k
= BN_new(); u
= BN_new();
2861 sdsa
->p
= BN_new(); sdsa
->q
= BN_new(); sdsa
->g
= BN_new();
2863 BN_rand(k
, BN_num_bits(dsa
->q
), 0, 0);
2864 BN_mod(k
, k
, dsa
->q
, bctx
);
2865 BN_gcd(u
, k
, dsa
->q
, bctx
);
2869 BN_mod_exp(u
, dsa
->g
, k
, dsa
->p
, bctx
); /* A r */
2870 BN_mod_mul(u
, u
, r
, dsa
->p
, bctx
);
2871 bighash(u
, sdsa
->p
);
2872 BN_mod_exp(sdsa
->q
, dsa
->priv_key
, k
, dsa
->p
, bctx
); /* gbar */
2873 BN_mod_exp(sdsa
->g
, dsa
->pub_key
, k
, dsa
->p
, bctx
); /* ghat */
2874 BN_CTX_free(bctx
); BN_free(k
); BN_free(r
); BN_free(u
);
2877 * Encode the values in ASN.1 and sign.
2879 tstamp
= crypto_time();
2880 memset(vp
, 0, sizeof(struct value
));
2881 vp
->tstamp
= htonl(tstamp
);
2882 vp
->fstamp
= htonl(mv_fstamp
);
2883 len
= i2d_DSAparams(sdsa
, NULL
);
2885 msyslog(LOG_ERR
, "crypto_bob3 %s\n",
2886 ERR_error_string(ERR_get_error(), NULL
));
2890 vp
->vallen
= htonl(len
);
2893 i2d_DSAparams(sdsa
, &ptr
);
2899 if (tstamp
< cinfo
->first
|| tstamp
> cinfo
->last
)
2902 vp
->sig
= emalloc(sign_siglen
);
2903 EVP_SignInit(&ctx
, sign_digest
);
2904 EVP_SignUpdate(&ctx
, (u_char
*)&vp
->tstamp
, 12);
2905 EVP_SignUpdate(&ctx
, vp
->ptr
, len
);
2906 if (EVP_SignFinal(&ctx
, vp
->sig
, &len
, sign_pkey
))
2907 vp
->siglen
= htonl(len
);
2913 * crypto_mv - verify Bob's response to Alice's challenge
2917 * XEVNT_PUB bad or missing public key
2918 * XEVNT_ID bad or missing group key
2919 * XEVNT_ERR protocol error
2920 * XEVNT_FSP bad filestamp
2924 struct exten
*ep
, /* extension pointer */
2925 struct peer
*peer
/* peer structure pointer */
2928 DSA
*dsa
; /* MV parameters */
2929 DSA
*sdsa
; /* DSA parameters */
2930 BN_CTX
*bctx
; /* BIGNUM context */
2937 * If the MV parameters are not valid or no challenge was sent,
2938 * something awful happened or we are being tormented.
2940 if (peer
->ident_pkey
== NULL
) {
2941 msyslog(LOG_INFO
, "crypto_mv: scheme unavailable");
2944 if (ntohl(ep
->fstamp
) != peer
->fstamp
) {
2945 msyslog(LOG_INFO
, "crypto_mv: invalid filestamp %u",
2949 if ((dsa
= peer
->ident_pkey
->pkey
.dsa
) == NULL
) {
2950 msyslog(LOG_INFO
, "crypto_mv: defective key");
2953 if (peer
->iffval
== NULL
) {
2954 msyslog(LOG_INFO
, "crypto_mv: missing challenge");
2959 * Extract the (hash(y), gbar, ghat) values from the response.
2961 bctx
= BN_CTX_new(); k
= BN_new(); u
= BN_new(); v
= BN_new();
2962 len
= ntohl(ep
->vallen
);
2963 ptr
= (const u_char
*)ep
->pkt
;
2964 if ((sdsa
= d2i_DSAparams(NULL
, &ptr
, len
)) == NULL
) {
2965 msyslog(LOG_ERR
, "crypto_mv %s\n",
2966 ERR_error_string(ERR_get_error(), NULL
));
2971 * Compute (gbar^xhat ghat^xbar)^-1 mod p.
2973 BN_mod_exp(u
, sdsa
->q
, dsa
->pub_key
, dsa
->p
, bctx
);
2974 BN_mod_exp(v
, sdsa
->g
, dsa
->priv_key
, dsa
->p
, bctx
);
2975 BN_mod_mul(u
, u
, v
, dsa
->p
, bctx
);
2976 BN_mod_inverse(u
, u
, dsa
->p
, bctx
);
2977 BN_mod_mul(v
, u
, peer
->iffval
, dsa
->p
, bctx
);
2980 * The result should match the hash of r mod p.
2983 temp
= BN_cmp(v
, sdsa
->p
);
2984 BN_CTX_free(bctx
); BN_free(k
); BN_free(u
); BN_free(v
);
2985 BN_free(peer
->iffval
);
2986 peer
->iffval
= NULL
;
2997 ***********************************************************************
2999 * The following routines are used to manipulate certificates *
3001 ***********************************************************************
3004 * cert_parse - parse x509 certificate and create info/value structures.
3006 * The server certificate includes the version number, issuer name,
3007 * subject name, public key and valid date interval. If the issuer name
3008 * is the same as the subject name, the certificate is self signed and
3009 * valid only if the server is configured as trustable. If the names are
3010 * different, another issuer has signed the server certificate and
3011 * vouched for it. In this case the server certificate is valid if
3012 * verified by the issuer public key.
3014 * Returns certificate info/value pointer if valid, NULL if not.
3016 struct cert_info
* /* certificate information structure */
3018 u_char
*asn1cert
, /* X509 certificate */
3019 u_int len
, /* certificate length */
3020 tstamp_t fstamp
/* filestamp */
3023 X509
*cert
; /* X509 certificate */
3024 X509_EXTENSION
*ext
; /* X509v3 extension */
3025 struct cert_info
*ret
; /* certificate info/value */
3027 const X509V3_EXT_METHOD
*method
;
3028 char pathbuf
[MAXFILENAME
];
3034 * Decode ASN.1 objects and construct certificate structure.
3037 if ((cert
= d2i_X509(NULL
, &uptr
, len
)) == NULL
) {
3038 msyslog(LOG_ERR
, "cert_parse %s\n",
3039 ERR_error_string(ERR_get_error(), NULL
));
3044 * Extract version, subject name and public key.
3046 ret
= emalloc(sizeof(struct cert_info
));
3047 memset(ret
, 0, sizeof(struct cert_info
));
3048 if ((ret
->pkey
= X509_get_pubkey(cert
)) == NULL
) {
3049 msyslog(LOG_ERR
, "cert_parse %s\n",
3050 ERR_error_string(ERR_get_error(), NULL
));
3055 ret
->version
= X509_get_version(cert
);
3056 X509_NAME_oneline(X509_get_subject_name(cert
), pathbuf
,
3058 ptr
= strstr(pathbuf
, "CN=");
3060 msyslog(LOG_INFO
, "cert_parse: invalid subject %s",
3066 ret
->subject
= emalloc(strlen(ptr
) + 1);
3067 strcpy(ret
->subject
, ptr
+ 3);
3070 * Extract remaining objects. Note that the NTP serial number is
3071 * the NTP seconds at the time of signing, but this might not be
3072 * the case for other authority. We don't bother to check the
3073 * objects at this time, since the real crunch can happen only
3074 * when the time is valid but not yet certificated.
3076 ret
->nid
= OBJ_obj2nid(cert
->cert_info
->signature
->algorithm
);
3077 ret
->digest
= (const EVP_MD
*)EVP_get_digestbynid(ret
->nid
);
3079 (u_long
)ASN1_INTEGER_get(X509_get_serialNumber(cert
));
3080 X509_NAME_oneline(X509_get_issuer_name(cert
), pathbuf
,
3082 if ((ptr
= strstr(pathbuf
, "CN=")) == NULL
) {
3083 msyslog(LOG_INFO
, "cert_parse: invalid issuer %s",
3089 ret
->issuer
= emalloc(strlen(ptr
) + 1);
3090 strcpy(ret
->issuer
, ptr
+ 3);
3091 ret
->first
= asn2ntp(X509_get_notBefore(cert
));
3092 ret
->last
= asn2ntp(X509_get_notAfter(cert
));
3095 * Extract extension fields. These are ad hoc ripoffs of
3096 * currently assigned functions and will certainly be changed
3097 * before prime time.
3099 cnt
= X509_get_ext_count(cert
);
3100 for (i
= 0; i
< cnt
; i
++) {
3101 ext
= X509_get_ext(cert
, i
);
3102 method
= X509V3_EXT_get(ext
);
3103 temp
= OBJ_obj2nid(ext
->object
);
3107 * If a key_usage field is present, we decode whether
3108 * this is a trusted or private certificate. This is
3109 * dorky; all we want is to compare NIDs, but OpenSSL
3110 * insists on BIO text strings.
3112 case NID_ext_key_usage
:
3113 bp
= BIO_new(BIO_s_mem());
3114 X509V3_EXT_print(bp
, ext
, 0, 0);
3115 BIO_gets(bp
, pathbuf
, MAXFILENAME
);
3119 printf("cert_parse: %s: %s\n",
3120 OBJ_nid2ln(temp
), pathbuf
);
3122 if (strcmp(pathbuf
, "Trust Root") == 0)
3123 ret
->flags
|= CERT_TRUST
;
3124 else if (strcmp(pathbuf
, "Private") == 0)
3125 ret
->flags
|= CERT_PRIV
;
3129 * If a NID_subject_key_identifier field is present, it
3130 * contains the GQ public key.
3132 case NID_subject_key_identifier
:
3133 ret
->grplen
= ext
->value
->length
- 2;
3134 ret
->grpkey
= emalloc(ret
->grplen
);
3135 memcpy(ret
->grpkey
, &ext
->value
->data
[2],
3142 * If certificate is self signed, verify signature.
3144 if (strcmp(ret
->subject
, ret
->issuer
) == 0) {
3145 if (!X509_verify(cert
, ret
->pkey
)) {
3147 "cert_parse: signature not verified %s",
3156 * Verify certificate valid times. Note that certificates cannot
3159 if (ret
->first
> ret
->last
|| ret
->first
< fstamp
) {
3161 "cert_parse: invalid certificate %s first %u last %u fstamp %u",
3162 ret
->subject
, ret
->first
, ret
->last
, fstamp
);
3169 * Build the value structure to sign and send later.
3171 ret
->cert
.fstamp
= htonl(fstamp
);
3172 ret
->cert
.vallen
= htonl(len
);
3173 ret
->cert
.ptr
= emalloc(len
);
3174 memcpy(ret
->cert
.ptr
, asn1cert
, len
);
3177 X509_print_fp(stdout
, cert
);
3185 * cert_sign - sign x509 certificate equest and update value structure.
3187 * The certificate request includes a copy of the host certificate,
3188 * which includes the version number, subject name and public key of the
3189 * host. The resulting certificate includes these values plus the
3190 * serial number, issuer name and valid interval of the server. The
3191 * valid interval extends from the current time to the same time one
3192 * year hence. This may extend the life of the signed certificate beyond
3193 * that of the signer certificate.
3195 * It is convenient to use the NTP seconds of the current time as the
3196 * serial number. In the value structure the timestamp is the current
3197 * time and the filestamp is taken from the extension field. Note this
3198 * routine is called only when the client clock is synchronized to a
3199 * proventic source, so timestamp comparisons are valid.
3201 * The host certificate is valid from the time it was generated for a
3202 * period of one year. A signed certificate is valid from the time of
3203 * signature for a period of one year, but only the host certificate (or
3204 * sign certificate if used) is actually used to encrypt and decrypt
3205 * signatures. The signature trail is built from the client via the
3206 * intermediate servers to the trusted server. Each signature on the
3207 * trail must be valid at the time of signature, but it could happen
3208 * that a signer certificate expire before the signed certificate, which
3209 * remains valid until its expiration.
3213 * XEVNT_PUB bad or missing public key
3214 * XEVNT_CRT bad or missing certificate
3215 * XEVNT_VFY certificate not verified
3216 * XEVNT_PER host certificate expired
3220 struct exten
*ep
, /* extension field pointer */
3221 struct value
*vp
/* value pointer */
3224 X509
*req
; /* X509 certificate request */
3225 X509
*cert
; /* X509 certificate */
3226 X509_EXTENSION
*ext
; /* certificate extension */
3227 ASN1_INTEGER
*serial
; /* serial number */
3228 X509_NAME
*subj
; /* distinguished (common) name */
3229 EVP_PKEY
*pkey
; /* public key */
3230 EVP_MD_CTX ctx
; /* message digest context */
3231 tstamp_t tstamp
; /* NTP timestamp */
3237 * Decode ASN.1 objects and construct certificate structure.
3238 * Make sure the system clock is synchronized to a proventic
3241 tstamp
= crypto_time();
3245 if (tstamp
< cinfo
->first
|| tstamp
> cinfo
->last
)
3248 ptr
= (u_char
*)ep
->pkt
;
3249 if ((req
= d2i_X509(NULL
, &ptr
, ntohl(ep
->vallen
))) == NULL
) {
3250 msyslog(LOG_ERR
, "cert_sign %s\n",
3251 ERR_error_string(ERR_get_error(), NULL
));
3255 * Extract public key and check for errors.
3257 if ((pkey
= X509_get_pubkey(req
)) == NULL
) {
3258 msyslog(LOG_ERR
, "cert_sign %s\n",
3259 ERR_error_string(ERR_get_error(), NULL
));
3265 * Generate X509 certificate signed by this server. For this
3266 * purpose the issuer name is the server name. Also copy any
3267 * extensions that might be present.
3270 X509_set_version(cert
, X509_get_version(req
));
3271 serial
= ASN1_INTEGER_new();
3272 ASN1_INTEGER_set(serial
, tstamp
);
3273 X509_set_serialNumber(cert
, serial
);
3274 X509_gmtime_adj(X509_get_notBefore(cert
), 0L);
3275 X509_gmtime_adj(X509_get_notAfter(cert
), YEAR
);
3276 subj
= X509_get_issuer_name(cert
);
3277 X509_NAME_add_entry_by_txt(subj
, "commonName", MBSTRING_ASC
,
3278 (u_char
*)sys_hostname
, strlen(sys_hostname
), -1, 0);
3279 subj
= X509_get_subject_name(req
);
3280 X509_set_subject_name(cert
, subj
);
3281 X509_set_pubkey(cert
, pkey
);
3282 ext
= X509_get_ext(req
, 0);
3283 temp
= X509_get_ext_count(req
);
3284 for (i
= 0; i
< temp
; i
++) {
3285 ext
= X509_get_ext(req
, i
);
3286 X509_add_ext(cert
, ext
, -1);
3291 * Sign and verify the certificate.
3293 X509_sign(cert
, sign_pkey
, sign_digest
);
3294 if (!X509_verify(cert
, sign_pkey
)) {
3295 printf("cert_sign\n%s\n",
3296 ERR_error_string(ERR_get_error(), NULL
));
3300 len
= i2d_X509(cert
, NULL
);
3303 * Build and sign the value structure. We have to sign it here,
3304 * since the response has to be returned right away. This is a
3307 memset(vp
, 0, sizeof(struct value
));
3308 vp
->tstamp
= htonl(tstamp
);
3309 vp
->fstamp
= ep
->fstamp
;
3310 vp
->vallen
= htonl(len
);
3311 vp
->ptr
= emalloc(len
);
3313 i2d_X509(cert
, (unsigned char **)&ptr
);
3315 vp
->sig
= emalloc(sign_siglen
);
3316 EVP_SignInit(&ctx
, sign_digest
);
3317 EVP_SignUpdate(&ctx
, (u_char
*)vp
, 12);
3318 EVP_SignUpdate(&ctx
, vp
->ptr
, len
);
3319 if (EVP_SignFinal(&ctx
, vp
->sig
, &len
, sign_pkey
))
3320 vp
->siglen
= htonl(len
);
3323 X509_print_fp(stdout
, cert
);
3331 * cert_valid - verify certificate with given public key
3333 * This is pretty ugly, as the certificate has to be verified in the
3334 * OpenSSL X509 structure, not in the DER format in the info/value
3339 * XEVNT_VFY certificate not verified
3343 struct cert_info
*cinf
, /* certificate information structure */
3344 EVP_PKEY
*pkey
/* public key */
3347 X509
*cert
; /* X509 certificate */
3350 if (cinf
->flags
& CERT_SIGN
)
3353 ptr
= (u_char
*)cinf
->cert
.ptr
;
3354 cert
= d2i_X509(NULL
, &ptr
, ntohl(cinf
->cert
.vallen
));
3355 if (cert
== NULL
|| !X509_verify(cert
, pkey
))
3364 * cert - install certificate in certificate list
3366 * This routine encodes an extension field into a certificate info/value
3367 * structure. It searches the certificate list for duplicates and
3368 * expunges whichever is older. It then searches the list for other
3369 * certificates that might be verified by this latest one. Finally, it
3370 * inserts this certificate first on the list.
3374 * XEVNT_FSP bad or missing filestamp
3375 * XEVNT_CRT bad or missing certificate
3379 struct exten
*ep
, /* cert info/value */
3380 struct peer
*peer
/* peer structure */
3383 struct cert_info
*cp
, *xp
, *yp
, **zp
;
3386 * Parse and validate the signed certificate. If valid,
3387 * construct the info/value structure; otherwise, scamper home.
3389 if ((cp
= cert_parse((u_char
*)ep
->pkt
, ntohl(ep
->vallen
),
3390 ntohl(ep
->fstamp
))) == NULL
)
3394 * Scan certificate list looking for another certificate with
3395 * the same subject and issuer. If another is found with the
3396 * same or older filestamp, unlink it and return the goodies to
3397 * the heap. If another is found with a later filestamp, discard
3398 * the new one and leave the building.
3400 * Make a note to study this issue again. An earlier certificate
3401 * with a long lifetime might be overtaken by a later
3402 * certificate with a short lifetime, thus invalidating the
3403 * earlier signature. However, we gotta find a way to leak old
3404 * stuff from the cache, so we do it anyway.
3408 for (xp
= cinfo
; xp
!= NULL
; xp
= xp
->link
) {
3409 if (strcmp(cp
->subject
, xp
->subject
) == 0 &&
3410 strcmp(cp
->issuer
, xp
->issuer
) == 0) {
3411 if (ntohl(cp
->cert
.fstamp
) <=
3412 ntohl(xp
->cert
.fstamp
)) {
3427 * Scan the certificate list to see if Y is signed by X. This is
3428 * independent of order.
3430 for (yp
= cinfo
; yp
!= NULL
; yp
= yp
->link
) {
3431 for (xp
= cinfo
; xp
!= NULL
; xp
= xp
->link
) {
3434 * If the issuer of certificate Y matches the
3435 * subject of certificate X, verify the
3436 * signature of Y using the public key of X. If
3439 if (strcmp(yp
->issuer
, xp
->subject
) != 0 ||
3440 xp
->flags
& CERT_ERROR
)
3443 if (cert_valid(yp
, xp
->pkey
) != XEVNT_OK
) {
3444 yp
->flags
|= CERT_ERROR
;
3449 * The signature Y is valid only if it begins
3450 * during the lifetime of X; however, it is not
3451 * necessarily an error, since some other
3452 * certificate might sign Y.
3454 if (yp
->first
< xp
->first
|| yp
->first
>
3458 yp
->flags
|= CERT_SIGN
;
3461 * If X is trusted, then Y is trusted. Note that
3462 * we might stumble over a self-signed
3463 * certificate that is not trusted, at least
3464 * temporarily. This can happen when a dude
3465 * first comes up, but has not synchronized the
3466 * clock and had its certificate signed by its
3467 * server. In case of broken certificate trail,
3468 * this might result in a loop that could
3469 * persist until timeout.
3471 if (!(xp
->flags
& (CERT_TRUST
| CERT_VALID
)))
3474 yp
->flags
|= CERT_VALID
;
3477 * If subject Y matches the server subject name,
3478 * then Y has completed the certificate trail.
3479 * Save the group key and light the valid bit.
3481 if (strcmp(yp
->subject
, peer
->subject
) != 0)
3484 if (yp
->grpkey
!= NULL
) {
3485 if (peer
->grpkey
!= NULL
)
3486 BN_free(peer
->grpkey
);
3487 peer
->grpkey
= BN_bin2bn(yp
->grpkey
,
3490 peer
->crypto
|= CRYPTO_FLAG_VALID
;
3493 * If the server has an an identity scheme,
3494 * fetch the identity credentials. If not, the
3495 * identity is verified only by the trusted
3496 * certificate. The next signature will set the
3499 if (peer
->crypto
& (CRYPTO_FLAG_GQ
|
3500 CRYPTO_FLAG_IFF
| CRYPTO_FLAG_MV
))
3503 peer
->crypto
|= CRYPTO_FLAG_VRFY
;
3508 * That was awesome. Now update the timestamps and signatures.
3516 * cert_free - free certificate information structure
3520 struct cert_info
*cinf
/* certificate info/value structure */
3523 if (cinf
->pkey
!= NULL
)
3524 EVP_PKEY_free(cinf
->pkey
);
3525 if (cinf
->subject
!= NULL
)
3526 free(cinf
->subject
);
3527 if (cinf
->issuer
!= NULL
)
3529 if (cinf
->grpkey
!= NULL
)
3531 value_free(&cinf
->cert
);
3537 ***********************************************************************
3539 * The following routines are used only at initialization time *
3541 ***********************************************************************
3544 * crypto_key - load cryptographic parameters and keys from files
3546 * This routine loads a PEM-encoded public/private key pair and extracts
3547 * the filestamp from the file name.
3549 * Returns public key pointer if valid, NULL if not. Side effect updates
3550 * the filestamp if valid.
3554 char *cp
, /* file name */
3555 tstamp_t
*fstamp
/* filestamp */
3558 FILE *str
; /* file handle */
3559 EVP_PKEY
*pkey
= NULL
; /* public/private key */
3560 char filename
[MAXFILENAME
]; /* name of key file */
3561 char linkname
[MAXFILENAME
]; /* filestamp buffer) */
3562 char statstr
[NTP_MAXSTRLEN
]; /* statistics for filegen */
3566 * Open the key file. If the first character of the file name is
3567 * not '/', prepend the keys directory string. If something goes
3568 * wrong, abandon ship.
3571 strcpy(filename
, cp
);
3573 snprintf(filename
, MAXFILENAME
, "%s/%s", keysdir
, cp
);
3574 str
= fopen(filename
, "r");
3579 * Read the filestamp, which is contained in the first line.
3581 if ((ptr
= fgets(linkname
, MAXFILENAME
, str
)) == NULL
) {
3582 msyslog(LOG_ERR
, "crypto_key: no data %s\n",
3587 if ((ptr
= strrchr(ptr
, '.')) == NULL
) {
3588 msyslog(LOG_ERR
, "crypto_key: no filestamp %s\n",
3593 if (sscanf(++ptr
, "%u", fstamp
) != 1) {
3594 msyslog(LOG_ERR
, "crypto_key: invalid timestamp %s\n",
3601 * Read and decrypt PEM-encoded private key.
3603 pkey
= PEM_read_PrivateKey(str
, NULL
, NULL
, passwd
);
3606 msyslog(LOG_ERR
, "crypto_key %s\n",
3607 ERR_error_string(ERR_get_error(), NULL
));
3612 * Leave tracks in the cryptostats.
3614 if ((ptr
= strrchr(linkname
, '\n')) != NULL
)
3616 snprintf(statstr
, NTP_MAXSTRLEN
, "%s mod %d", &linkname
[2],
3617 EVP_PKEY_size(pkey
) * 8);
3618 record_crypto_stats(NULL
, statstr
);
3621 printf("crypto_key: %s\n", statstr
);
3623 if (pkey
->type
== EVP_PKEY_DSA
)
3624 DSA_print_fp(stdout
, pkey
->pkey
.dsa
, 0);
3626 RSA_print_fp(stdout
, pkey
->pkey
.rsa
, 0);
3634 * crypto_cert - load certificate from file
3636 * This routine loads a X.509 RSA or DSA certificate from a file and
3637 * constructs a info/cert value structure for this machine. The
3638 * structure includes a filestamp extracted from the file name. Later
3639 * the certificate can be sent to another machine by request.
3641 * Returns certificate info/value pointer if valid, NULL if not.
3643 static struct cert_info
* /* certificate information */
3645 char *cp
/* file name */
3648 struct cert_info
*ret
; /* certificate information */
3649 FILE *str
; /* file handle */
3650 char filename
[MAXFILENAME
]; /* name of certificate file */
3651 char linkname
[MAXFILENAME
]; /* filestamp buffer */
3652 char statstr
[NTP_MAXSTRLEN
]; /* statistics for filegen */
3653 tstamp_t fstamp
; /* filestamp */
3656 char *name
, *header
;
3660 * Open the certificate file. If the first character of the file
3661 * name is not '/', prepend the keys directory string. If
3662 * something goes wrong, abandon ship.
3665 strcpy(filename
, cp
);
3667 snprintf(filename
, MAXFILENAME
, "%s/%s", keysdir
, cp
);
3668 str
= fopen(filename
, "r");
3673 * Read the filestamp, which is contained in the first line.
3675 if ((ptr
= fgets(linkname
, MAXFILENAME
, str
)) == NULL
) {
3676 msyslog(LOG_ERR
, "crypto_cert: no data %s\n",
3681 if ((ptr
= strrchr(ptr
, '.')) == NULL
) {
3682 msyslog(LOG_ERR
, "crypto_cert: no filestamp %s\n",
3687 if (sscanf(++ptr
, "%u", &fstamp
) != 1) {
3688 msyslog(LOG_ERR
, "crypto_cert: invalid filestamp %s\n",
3695 * Read PEM-encoded certificate and install.
3697 if (!PEM_read(str
, &name
, &header
, &data
, &len
)) {
3698 msyslog(LOG_ERR
, "crypto_cert %s\n",
3699 ERR_error_string(ERR_get_error(), NULL
));
3704 if (strcmp(name
, "CERTIFICATE") !=0) {
3705 msyslog(LOG_INFO
, "crypto_cert: wrong PEM type %s",
3715 * Parse certificate and generate info/value structure.
3717 ret
= cert_parse(data
, len
, fstamp
);
3723 if ((ptr
= strrchr(linkname
, '\n')) != NULL
)
3725 snprintf(statstr
, NTP_MAXSTRLEN
,
3726 "%s 0x%x len %lu", &linkname
[2], ret
->flags
, len
);
3727 record_crypto_stats(NULL
, statstr
);
3730 printf("crypto_cert: %s\n", statstr
);
3737 * crypto_tai - load leapseconds table from file
3739 * This routine loads the ERTS leapsecond file in NIST text format,
3740 * converts to a value structure and extracts a filestamp from the file
3741 * name. The data are used to establish the TAI offset from UTC, which
3742 * is provided to the kernel if supported. Later the data can be sent to
3743 * another machine on request.
3747 char *cp
/* file name */
3750 FILE *str
; /* file handle */
3751 char buf
[NTP_MAXSTRLEN
]; /* file line buffer */
3752 u_int32 leapsec
[MAX_LEAP
]; /* NTP time at leaps */
3753 int offset
; /* offset at leap (s) */
3754 char filename
[MAXFILENAME
]; /* name of leapseconds file */
3755 char linkname
[MAXFILENAME
]; /* file link (for filestamp) */
3756 char statstr
[NTP_MAXSTRLEN
]; /* statistics for filegen */
3757 tstamp_t fstamp
; /* filestamp */
3764 * Open the file and discard comment lines. If the first
3765 * character of the file name is not '/', prepend the keys
3766 * directory string. If the file is not found, not to worry; it
3767 * can be retrieved over the net. But, if it is found with
3768 * errors, we crash and burn.
3771 strcpy(filename
, cp
);
3773 snprintf(filename
, MAXFILENAME
, "%s/%s", keysdir
, cp
);
3774 if ((str
= fopen(filename
, "r")) == NULL
)
3778 * Extract filestamp if present.
3780 rval
= readlink(filename
, linkname
, MAXFILENAME
- 1);
3782 linkname
[rval
] = '\0';
3783 dp
= strrchr(linkname
, '.');
3785 dp
= strrchr(filename
, '.');
3788 sscanf(++dp
, "%u", &fstamp
);
3791 tai_leap
.fstamp
= htonl(fstamp
);
3794 * We are rather paranoid here, since an intruder might cause a
3795 * coredump by infiltrating naughty values. Empty lines and
3796 * comments are ignored. Other lines must begin with two
3797 * integers followed by junk or comments. The first integer is
3798 * the NTP seconds of leap insertion, the second is the offset
3799 * of TAI relative to UTC after that insertion. The second word
3800 * must equal the initial insertion of ten seconds on 1 January
3801 * 1972 plus one second for each succeeding insertion.
3804 while (i
< MAX_LEAP
) {
3805 dp
= fgets(buf
, NTP_MAXSTRLEN
- 1, str
);
3809 if (strlen(buf
) < 1)
3815 if (sscanf(buf
, "%u %d", &leapsec
[i
], &offset
) != 2)
3818 if (i
!= offset
- TAI_1972
)
3826 "crypto_tai: leapseconds file %s error %d", cp
,
3832 * The extension field table entries consists of the NTP seconds
3833 * of leap insertion in network byte order.
3835 len
= i
* sizeof(u_int32
);
3836 tai_leap
.vallen
= htonl(len
);
3838 tai_leap
.ptr
= (u_char
*)ptr
;
3839 for (j
= 0; j
< i
; j
++)
3840 *ptr
++ = htonl(leapsec
[j
]);
3841 crypto_flags
|= CRYPTO_FLAG_TAI
;
3842 snprintf(statstr
, NTP_MAXSTRLEN
, "%s fs %u leap %u len %u", cp
, fstamp
,
3844 record_crypto_stats(NULL
, statstr
);
3847 printf("crypto_tai: %s\n", statstr
);
3853 * crypto_setup - load keys, certificate and leapseconds table
3855 * This routine loads the public/private host key and certificate. If
3856 * available, it loads the public/private sign key, which defaults to
3857 * the host key, and leapseconds table. The host key must be RSA, but
3858 * the sign key can be either RSA or DSA. In either case, the public key
3859 * on the certificate must agree with the sign key.
3864 EVP_PKEY
*pkey
; /* private/public key pair */
3865 char filename
[MAXFILENAME
]; /* file name buffer */
3866 l_fp seed
; /* crypto PRNG seed as NTP timestamp */
3867 tstamp_t fstamp
; /* filestamp */
3868 tstamp_t sstamp
; /* sign filestamp */
3873 * Initialize structures.
3878 gethostname(filename
, MAXFILENAME
);
3879 bytes
= strlen(filename
) + 1;
3880 sys_hostname
= emalloc(bytes
);
3881 memcpy(sys_hostname
, filename
, bytes
);
3883 passwd
= sys_hostname
;
3884 memset(&hostval
, 0, sizeof(hostval
));
3885 memset(&pubkey
, 0, sizeof(pubkey
));
3886 memset(&tai_leap
, 0, sizeof(tai_leap
));
3889 * Load required random seed file and seed the random number
3890 * generator. Be default, it is found in the user home
3891 * directory. The root home directory may be / or /root,
3892 * depending on the system. Wiggle the contents a bit and write
3893 * it back so the sequence does not repeat when we next restart.
3895 ERR_load_crypto_strings();
3896 if (rand_file
== NULL
) {
3897 if ((RAND_file_name(filename
, MAXFILENAME
)) != NULL
) {
3898 rand_file
= emalloc(strlen(filename
) + 1);
3899 strcpy(rand_file
, filename
);
3901 } else if (*rand_file
!= '/') {
3902 snprintf(filename
, MAXFILENAME
, "%s/%s", keysdir
,
3905 rand_file
= emalloc(strlen(filename
) + 1);
3906 strcpy(rand_file
, filename
);
3908 if (rand_file
== NULL
) {
3910 "crypto_setup: random seed file not specified");
3913 if ((bytes
= RAND_load_file(rand_file
, -1)) == 0) {
3915 "crypto_setup: random seed file %s not found\n",
3920 RAND_seed(&seed
, sizeof(l_fp
));
3921 RAND_write_file(rand_file
);
3922 OpenSSL_add_all_algorithms();
3926 "crypto_setup: OpenSSL version %lx random seed file %s bytes read %d\n",
3927 SSLeay(), rand_file
, bytes
);
3931 * Load required host key from file "ntpkey_host_<hostname>". It
3932 * also becomes the default sign key.
3934 if (host_file
== NULL
) {
3935 snprintf(filename
, MAXFILENAME
, "ntpkey_host_%s",
3937 host_file
= emalloc(strlen(filename
) + 1);
3938 strcpy(host_file
, filename
);
3940 pkey
= crypto_key(host_file
, &fstamp
);
3943 "crypto_setup: host key file %s not found or corrupt",
3950 hostval
.fstamp
= htonl(fstamp
);
3951 if (host_pkey
->type
!= EVP_PKEY_RSA
) {
3953 "crypto_setup: host key is not RSA key type");
3956 hostval
.vallen
= htonl(strlen(sys_hostname
));
3957 hostval
.ptr
= (u_char
*)sys_hostname
;
3960 * Construct public key extension field for agreement scheme.
3962 len
= i2d_PublicKey(host_pkey
, NULL
);
3965 i2d_PublicKey(host_pkey
, &ptr
);
3966 pubkey
.vallen
= htonl(len
);
3967 pubkey
.fstamp
= hostval
.fstamp
;
3970 * Load optional sign key from file "ntpkey_sign_<hostname>". If
3971 * loaded, it becomes the sign key.
3973 if (sign_file
== NULL
) {
3974 snprintf(filename
, MAXFILENAME
, "ntpkey_sign_%s",
3976 sign_file
= emalloc(strlen(filename
) + 1);
3977 strcpy(sign_file
, filename
);
3979 pkey
= crypto_key(sign_file
, &fstamp
);
3984 sign_siglen
= EVP_PKEY_size(sign_pkey
);
3987 * Load optional IFF parameters from file
3988 * "ntpkey_iff_<hostname>".
3990 if (iffpar_file
== NULL
) {
3991 snprintf(filename
, MAXFILENAME
, "ntpkey_iff_%s",
3993 iffpar_file
= emalloc(strlen(filename
) + 1);
3994 strcpy(iffpar_file
, filename
);
3996 iffpar_pkey
= crypto_key(iffpar_file
, &if_fstamp
);
3997 if (iffpar_pkey
!= NULL
)
3998 crypto_flags
|= CRYPTO_FLAG_IFF
;
4001 * Load optional GQ parameters from file "ntpkey_gq_<hostname>".
4003 if (gqpar_file
== NULL
) {
4004 snprintf(filename
, MAXFILENAME
, "ntpkey_gq_%s",
4006 gqpar_file
= emalloc(strlen(filename
) + 1);
4007 strcpy(gqpar_file
, filename
);
4009 gqpar_pkey
= crypto_key(gqpar_file
, &gq_fstamp
);
4010 if (gqpar_pkey
!= NULL
)
4011 crypto_flags
|= CRYPTO_FLAG_GQ
;
4014 * Load optional MV parameters from file "ntpkey_mv_<hostname>".
4016 if (mvpar_file
== NULL
) {
4017 snprintf(filename
, MAXFILENAME
, "ntpkey_mv_%s",
4019 mvpar_file
= emalloc(strlen(filename
) + 1);
4020 strcpy(mvpar_file
, filename
);
4022 mvpar_pkey
= crypto_key(mvpar_file
, &mv_fstamp
);
4023 if (mvpar_pkey
!= NULL
)
4024 crypto_flags
|= CRYPTO_FLAG_MV
;
4027 * Load required certificate from file "ntpkey_cert_<hostname>".
4029 if (cert_file
== NULL
) {
4030 snprintf(filename
, MAXFILENAME
, "ntpkey_cert_%s",
4032 cert_file
= emalloc(strlen(filename
) + 1);
4033 strcpy(cert_file
, filename
);
4035 if ((cinfo
= crypto_cert(cert_file
)) == NULL
) {
4037 "certificate file %s not found or corrupt",
4043 * The subject name must be the same as the host name, unless
4044 * the certificate is private, in which case it may have come
4045 * from another host.
4047 if (!(cinfo
->flags
& CERT_PRIV
) && strcmp(cinfo
->subject
,
4048 sys_hostname
) != 0) {
4050 "crypto_setup: certificate %s not for this host",
4057 * It the certificate is trusted, the subject must be the same
4058 * as the issuer, in other words it must be self signed.
4060 if (cinfo
->flags
& CERT_TRUST
&& strcmp(cinfo
->subject
,
4061 cinfo
->issuer
) != 0) {
4062 if (cert_valid(cinfo
, sign_pkey
) != XEVNT_OK
) {
4064 "crypto_setup: certificate %s is trusted, but not self signed.",
4070 sign_digest
= cinfo
->digest
;
4071 if (cinfo
->flags
& CERT_PRIV
)
4072 crypto_flags
|= CRYPTO_FLAG_PRIV
;
4073 crypto_flags
|= cinfo
->nid
<< 16;
4076 * Load optional leapseconds table from file "ntpkey_leap". If
4077 * the file is missing or defective, the values can later be
4078 * retrieved from a server.
4080 if (leap_file
== NULL
)
4081 leap_file
= "ntpkey_leap";
4082 crypto_tai(leap_file
);
4086 "crypto_setup: flags 0x%x host %s signature %s\n",
4087 crypto_flags
, sys_hostname
, OBJ_nid2ln(cinfo
->nid
));
4093 * crypto_config - configure data from crypto configuration command.
4097 int item
, /* configuration item */
4098 char *cp
/* file name */
4104 * Set random seed file name.
4106 case CRYPTO_CONF_RAND
:
4107 rand_file
= emalloc(strlen(cp
) + 1);
4108 strcpy(rand_file
, cp
);
4112 * Set private key password.
4114 case CRYPTO_CONF_PW
:
4115 passwd
= emalloc(strlen(cp
) + 1);
4120 * Set host file name.
4122 case CRYPTO_CONF_PRIV
:
4123 host_file
= emalloc(strlen(cp
) + 1);
4124 strcpy(host_file
, cp
);
4128 * Set sign key file name.
4130 case CRYPTO_CONF_SIGN
:
4131 sign_file
= emalloc(strlen(cp
) + 1);
4132 strcpy(sign_file
, cp
);
4136 * Set iff parameters file name.
4138 case CRYPTO_CONF_IFFPAR
:
4139 iffpar_file
= emalloc(strlen(cp
) + 1);
4140 strcpy(iffpar_file
, cp
);
4144 * Set gq parameters file name.
4146 case CRYPTO_CONF_GQPAR
:
4147 gqpar_file
= emalloc(strlen(cp
) + 1);
4148 strcpy(gqpar_file
, cp
);
4152 * Set mv parameters file name.
4154 case CRYPTO_CONF_MVPAR
:
4155 mvpar_file
= emalloc(strlen(cp
) + 1);
4156 strcpy(mvpar_file
, cp
);
4160 * Set identity scheme.
4162 case CRYPTO_CONF_IDENT
:
4163 if (!strcasecmp(cp
, "iff"))
4164 ident_scheme
|= CRYPTO_FLAG_IFF
;
4165 else if (!strcasecmp(cp
, "gq"))
4166 ident_scheme
|= CRYPTO_FLAG_GQ
;
4167 else if (!strcasecmp(cp
, "mv"))
4168 ident_scheme
|= CRYPTO_FLAG_MV
;
4172 * Set certificate file name.
4174 case CRYPTO_CONF_CERT
:
4175 cert_file
= emalloc(strlen(cp
) + 1);
4176 strcpy(cert_file
, cp
);
4180 * Set leapseconds file name.
4182 case CRYPTO_CONF_LEAP
:
4183 leap_file
= emalloc(strlen(cp
) + 1);
4184 strcpy(leap_file
, cp
);
4187 crypto_flags
|= CRYPTO_FLAG_ENAB
;
4190 int ntp_crypto_bs_pubkey
;
4191 # endif /* OPENSSL */