1 /* $NetBSD: ntp_crypto.c,v 1.1.1.1 2009/12/13 16:55:33 kardel 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"
22 #include "ntp_assert.h"
24 #include "openssl/asn1_mac.h"
25 #include "openssl/bn.h"
26 #include "openssl/err.h"
27 #include "openssl/evp.h"
28 #include "openssl/pem.h"
29 #include "openssl/rand.h"
30 #include "openssl/x509v3.h"
33 #include "ntp_syscall.h"
34 #endif /* KERNEL_PLL */
37 * Extension field message format
39 * These are always signed and saved before sending in network byte
40 * order. They must be converted to and from host byte order for
44 * | op | len | <- extension pointer
48 * | timestamp | <- value pointer
65 * The CRYPTO_RESP bit is set to 0 for requests, 1 for responses.
66 * Requests carry the association ID of the receiver; responses carry
67 * the association ID of the sender. Some messages include only the
68 * operation/length and association ID words and so have length 8
69 * octets. Ohers include the value structure and associated value and
70 * signature fields. These messages include the timestamp, filestamp,
71 * value and signature words and so have length at least 24 octets. The
72 * signature and/or value fields can be empty, in which case the
73 * respective length words are zero. An empty value with nonempty
74 * signature is syntactically valid, but semantically questionable.
76 * The filestamp represents the time when a cryptographic data file such
77 * as a public/private key pair is created. It follows every reference
78 * depending on that file and serves as a means to obsolete earlier data
79 * of the same type. The timestamp represents the time when the
80 * cryptographic data of the message were last signed. Creation of a
81 * cryptographic data file or signing a message can occur only when the
82 * creator or signor is synchronized to an authoritative source and
83 * proventicated to a trusted authority.
85 * Note there are several conditions required for server trust. First,
86 * the public key on the server certificate must be verified, which can
87 * involve a hike along the certificate trail to a trusted host. Next,
88 * the server trust must be confirmed by one of several identity
89 * schemes. Valid cryptographic values are signed with attached
90 * timestamp and filestamp. Individual packet trust is confirmed
91 * relative to these values by a message digest with keys generated by a
92 * reverse-order pseudorandom hash.
94 * State decomposition. These flags are lit in the order given. They are
95 * dim only when the association is demobilized.
97 * CRYPTO_FLAG_ENAB Lit upon acceptance of a CRYPTO_ASSOC message
98 * CRYPTO_FLAG_CERT Lit when a self-digned trusted certificate is
100 * CRYPTO_FLAG_VRFY Lit when identity is confirmed.
101 * CRYPTO_FLAG_PROV Lit when the first signature is verified.
102 * CRYPTO_FLAG_COOK Lit when a valid cookie is accepted.
103 * CRYPTO_FLAG_AUTO Lit when valid autokey values are accepted.
104 * CRYPTO_FLAG_SIGN Lit when the server signed certificate is
106 * CRYPTO_FLAG_LEAP Lit when the leapsecond values are accepted.
111 #define TAI_1972 10 /* initial TAI offset (s) */
112 #define MAX_LEAP 100 /* max UTC leapseconds (s) */
113 #define VALUE_LEN (6 * 4) /* min response field length */
114 #define YEAR (60 * 60 * 24 * 365) /* seconds in year */
117 * Global cryptodata in host byte order
119 u_int32 crypto_flags
= 0x0; /* status word */
120 int crypto_nid
= KEY_TYPE_MD5
; /* digest nid */
121 char *sys_hostname
= NULL
; /* host name */
122 char *sys_groupname
= NULL
; /* group name */
125 * Global cryptodata in network byte order
127 struct cert_info
*cinfo
= NULL
; /* certificate info/value cache */
128 struct cert_info
*cert_host
= NULL
; /* host certificate */
129 struct pkey_info
*pkinfo
= NULL
; /* key info/value cache */
130 struct value hostval
; /* host value */
131 struct value pubkey
; /* public key */
132 struct value tai_leap
; /* leapseconds values */
133 struct pkey_info
*iffkey_info
= NULL
; /* IFF keys */
134 struct pkey_info
*gqkey_info
= NULL
; /* GQ keys */
135 struct pkey_info
*mvkey_info
= NULL
; /* MV keys */
138 * Private cryptodata in host byte order
140 static char *passwd
= NULL
; /* private key password */
141 static EVP_PKEY
*host_pkey
= NULL
; /* host key */
142 static EVP_PKEY
*sign_pkey
= NULL
; /* sign key */
143 static const EVP_MD
*sign_digest
= NULL
; /* sign digest */
144 static u_int sign_siglen
; /* sign key length */
145 static char *rand_file
= NULL
; /* random seed file */
150 static int crypto_verify (struct exten
*, struct value
*,
152 static int crypto_encrypt (struct exten
*, struct value
*,
154 static int crypto_alice (struct peer
*, struct value
*);
155 static int crypto_alice2 (struct peer
*, struct value
*);
156 static int crypto_alice3 (struct peer
*, struct value
*);
157 static int crypto_bob (struct exten
*, struct value
*);
158 static int crypto_bob2 (struct exten
*, struct value
*);
159 static int crypto_bob3 (struct exten
*, struct value
*);
160 static int crypto_iff (struct exten
*, struct peer
*);
161 static int crypto_gq (struct exten
*, struct peer
*);
162 static int crypto_mv (struct exten
*, struct peer
*);
163 static int crypto_send (struct exten
*, struct value
*, int);
164 static tstamp_t
crypto_time (void);
165 static u_long
asn2ntp (ASN1_TIME
*);
166 static struct cert_info
*cert_parse (u_char
*, long, tstamp_t
);
167 static int cert_sign (struct exten
*, struct value
*);
168 static struct cert_info
*cert_install (struct exten
*, struct peer
*);
169 static int cert_hike (struct peer
*, struct cert_info
*);
170 static void cert_free (struct cert_info
*);
171 static struct pkey_info
*crypto_key (char *, char *, sockaddr_u
*);
172 static void bighash (BIGNUM
*, BIGNUM
*);
173 static struct cert_info
*crypto_cert (char *);
177 readlink(char * link
, char * file
, int len
) {
183 * session_key - generate session key
185 * This routine generates a session key from the source address,
186 * destination address, key ID and private value. The value of the
187 * session key is the MD5 hash of these values, while the next key ID is
188 * the first four octets of the hash.
190 * Returns the next key ID or 0 if there is no destination address.
194 sockaddr_u
*srcadr
, /* source address */
195 sockaddr_u
*dstadr
, /* destination address */
196 keyid_t keyno
, /* key ID */
197 keyid_t
private, /* private value */
198 u_long lifetime
/* key lifetime */
201 EVP_MD_CTX ctx
; /* message digest context */
202 u_char dgst
[EVP_MAX_MD_SIZE
]; /* message digest */
203 keyid_t keyid
; /* key identifer */
204 u_int32 header
[10]; /* data in network byte order */
211 * Generate the session key and key ID. If the lifetime is
212 * greater than zero, install the key and call it trusted.
217 header
[0] = NSRCADR(srcadr
);
218 header
[1] = NSRCADR(dstadr
);
219 header
[2] = htonl(keyno
);
220 header
[3] = htonl(private);
221 hdlen
= 4 * sizeof(u_int32
);
225 memcpy(&header
[0], PSOCK_ADDR6(srcadr
),
226 sizeof(struct in6_addr
));
227 memcpy(&header
[4], PSOCK_ADDR6(dstadr
),
228 sizeof(struct in6_addr
));
229 header
[8] = htonl(keyno
);
230 header
[9] = htonl(private);
231 hdlen
= 10 * sizeof(u_int32
);
234 EVP_DigestInit(&ctx
, EVP_get_digestbynid(crypto_nid
));
235 EVP_DigestUpdate(&ctx
, (u_char
*)header
, hdlen
);
236 EVP_DigestFinal(&ctx
, dgst
, &len
);
237 memcpy(&keyid
, dgst
, 4);
238 keyid
= ntohl(keyid
);
240 MD5auth_setkey(keyno
, crypto_nid
, dgst
, len
);
241 authtrust(keyno
, lifetime
);
243 DPRINTF(2, ("session_key: %s > %s %08x %08x hash %08x life %lu\n",
244 stoa(srcadr
), stoa(dstadr
), keyno
,
245 private, keyid
, lifetime
));
252 * make_keylist - generate key list
256 * XEVNT_ERR protocol error
258 * This routine constructs a pseudo-random sequence by repeatedly
259 * hashing the session key starting from a given source address,
260 * destination address, private value and the next key ID of the
261 * preceeding session key. The last entry on the list is saved along
262 * with its sequence number and public signature.
266 struct peer
*peer
, /* peer structure pointer */
267 struct interface
*dstadr
/* interface */
270 EVP_MD_CTX ctx
; /* signature context */
271 tstamp_t tstamp
; /* NTP timestamp */
272 struct autokey
*ap
; /* autokey pointer */
273 struct value
*vp
; /* value pointer */
274 keyid_t keyid
= 0; /* next key ID */
275 keyid_t cookie
; /* private value */
284 * Allocate the key list if necessary.
286 tstamp
= crypto_time();
287 if (peer
->keylist
== NULL
)
288 peer
->keylist
= emalloc(sizeof(keyid_t
) *
292 * Generate an initial key ID which is unique and greater than
296 keyid
= ntp_random() & 0xffffffff;
297 if (keyid
<= NTP_MAXKEY
)
300 if (authhavekey(keyid
))
306 * Generate up to NTP_MAXSESSION session keys. Stop if the
307 * next one would not be unique or not a session key ID or if
308 * it would expire before the next poll. The private value
309 * included in the hash is zero if broadcast mode, the peer
310 * cookie if client mode or the host cookie if symmetric modes.
312 mpoll
= 1 << min(peer
->ppoll
, peer
->hpoll
);
313 lifetime
= min(1 << sys_automax
, NTP_MAXSESSION
* mpoll
);
314 if (peer
->hmode
== MODE_BROADCAST
)
317 cookie
= peer
->pcookie
;
318 for (i
= 0; i
< NTP_MAXSESSION
; i
++) {
319 peer
->keylist
[i
] = keyid
;
321 keyid
= session_key(&dstadr
->sin
, &peer
->srcadr
, keyid
,
322 cookie
, lifetime
+ mpoll
);
324 if (auth_havekey(keyid
) || keyid
<= NTP_MAXKEY
||
325 lifetime
< 0 || tstamp
== 0)
330 * Save the last session key ID, sequence number and timestamp,
331 * then sign these values for later retrieval by the clients. Be
332 * careful not to use invalid key media. Use the public values
333 * timestamp as filestamp.
337 vp
->ptr
= emalloc(sizeof(struct autokey
));
338 ap
= (struct autokey
*)vp
->ptr
;
339 ap
->seq
= htonl(peer
->keynumber
);
340 ap
->key
= htonl(keyid
);
341 vp
->tstamp
= htonl(tstamp
);
342 vp
->fstamp
= hostval
.tstamp
;
343 vp
->vallen
= htonl(sizeof(struct autokey
));
347 vp
->sig
= emalloc(sign_siglen
);
348 EVP_SignInit(&ctx
, sign_digest
);
349 EVP_SignUpdate(&ctx
, (u_char
*)vp
, 12);
350 EVP_SignUpdate(&ctx
, vp
->ptr
, sizeof(struct autokey
));
351 if (EVP_SignFinal(&ctx
, vp
->sig
, &len
, sign_pkey
)) {
352 vp
->siglen
= htonl(sign_siglen
);
353 peer
->flags
|= FLAG_ASSOC
;
358 printf("make_keys: %d %08x %08x ts %u fs %u poll %d\n",
359 peer
->keynumber
, keyid
, cookie
, ntohl(vp
->tstamp
),
360 ntohl(vp
->fstamp
), peer
->hpoll
);
367 * crypto_recv - parse extension fields
369 * This routine is called when the packet has been matched to an
370 * association and passed sanity, format and MAC checks. We believe the
371 * extension field values only if the field has proper format and
372 * length, the timestamp and filestamp are valid and the signature has
373 * valid length and is verified. There are a few cases where some values
374 * are believed even if the signature fails, but only if the proventic
379 * XEVNT_ERR protocol error
380 * XEVNT_LEN bad field format or length
384 struct peer
*peer
, /* peer structure pointer */
385 struct recvbuf
*rbufp
/* packet buffer pointer */
388 const EVP_MD
*dp
; /* message digest algorithm */
389 u_int32
*pkt
; /* receive packet pointer */
390 struct autokey
*ap
, *bp
; /* autokey pointer */
391 struct exten
*ep
, *fp
; /* extension pointers */
392 struct cert_info
*xinfo
; /* certificate info pointer */
393 int has_mac
; /* length of MAC field */
394 int authlen
; /* offset of MAC field */
395 associd_t associd
; /* association ID */
396 tstamp_t tstamp
= 0; /* timestamp */
397 tstamp_t fstamp
= 0; /* filestamp */
398 u_int len
; /* extension field length */
399 u_int code
; /* extension field opcode */
400 u_int vallen
= 0; /* value length */
401 X509
*cert
; /* X509 certificate */
402 char statstr
[NTP_MAXSTRLEN
]; /* statistics for filegen */
403 keyid_t cookie
; /* crumbles */
404 int hismode
; /* packet mode */
410 * Initialize. Note that the packet has already been checked for
411 * valid format and extension field lengths. First extract the
412 * field length, command code and association ID in host byte
413 * order. These are used with all commands and modes. Then check
414 * the version number, which must be 2, and length, which must
415 * be at least 8 for requests and VALUE_LEN (24) for responses.
416 * Packets that fail either test sink without a trace. The
417 * association ID is saved only if nonzero.
419 authlen
= LEN_PKT_NOMAC
;
420 hismode
= (int)PKT_MODE((&rbufp
->recv_pkt
)->li_vn_mode
);
421 while ((has_mac
= rbufp
->recv_length
- authlen
) > MAX_MAC_LEN
) {
422 pkt
= (u_int32
*)&rbufp
->recv_pkt
+ authlen
/ 4;
423 ep
= (struct exten
*)pkt
;
424 code
= ntohl(ep
->opcode
) & 0xffff0000;
425 len
= ntohl(ep
->opcode
) & 0x0000ffff;
426 associd
= (associd_t
)ntohl(pkt
[1]);
431 "crypto_recv: flags 0x%x ext offset %d len %u code 0x%x associd %d\n",
432 peer
->crypto
, authlen
, len
, code
>> 16,
437 * Check version number and field length. If bad,
438 * quietly ignore the packet.
440 if (((code
>> 24) & 0x3f) != CRYPTO_VN
|| len
< 8) {
442 code
|= CRYPTO_ERROR
;
445 if (len
>= VALUE_LEN
) {
446 tstamp
= ntohl(ep
->tstamp
);
447 fstamp
= ntohl(ep
->fstamp
);
448 vallen
= ntohl(ep
->vallen
);
453 * Install status word, host name, signature scheme and
454 * association ID. In OpenSSL the signature algorithm is
455 * bound to the digest algorithm, so the NID completely
456 * defines the signature scheme. Note the request and
457 * response are identical, but neither is validated by
458 * signature. The request is processed here only in
459 * symmetric modes. The server name field might be
460 * useful to implement access controls in future.
465 * If our state machine is running when this
466 * message arrives, the other fellow might have
467 * restarted. However, this could be an
468 * intruder, so just clamp the poll interval and
469 * find out for ourselves. Otherwise, pass the
470 * extension field to the transmit side.
472 if (peer
->crypto
& CRYPTO_FLAG_CERT
) {
477 if (peer
->assoc
!= associd
) {
484 fp
->associd
= htonl(peer
->associd
);
488 case CRYPTO_ASSOC
| CRYPTO_RESP
:
491 * Discard the message if it has already been
492 * stored or the message has been amputated.
495 if (peer
->assoc
!= associd
)
499 if (vallen
== 0 || vallen
> MAXHOSTNAME
||
500 len
< VALUE_LEN
+ vallen
) {
507 "crypto_recv: ident host 0x%x %d server 0x%x %d\n",
508 crypto_flags
, peer
->associd
, fstamp
,
511 temp32
= crypto_flags
& CRYPTO_FLAG_MASK
;
514 * If the client scheme is PC, the server scheme
515 * must be PC. The public key and identity are
516 * presumed valid, so we skip the certificate
517 * and identity exchanges and move immediately
518 * to the cookie exchange which confirms the
521 if (crypto_flags
& CRYPTO_FLAG_PRIV
) {
522 if (!(fstamp
& CRYPTO_FLAG_PRIV
)) {
526 fstamp
|= CRYPTO_FLAG_CERT
|
527 CRYPTO_FLAG_VRFY
| CRYPTO_FLAG_SIGN
;
530 * It is an error if either peer supports
531 * identity, but the other does not.
533 } else if (hismode
== MODE_ACTIVE
|| hismode
==
535 if ((temp32
&& !(fstamp
&
536 CRYPTO_FLAG_MASK
)) ||
537 (!temp32
&& (fstamp
&
538 CRYPTO_FLAG_MASK
))) {
545 * Discard the message if the signature digest
546 * NID is not supported.
548 temp32
= (fstamp
>> 16) & 0xffff;
550 (const EVP_MD
*)EVP_get_digestbynid(temp32
);
557 * Save status word, host name and message
558 * digest/signature type. If this is from a
559 * broadcast and the association ID has changed,
560 * request the autokey values.
562 peer
->assoc
= associd
;
563 if (hismode
== MODE_SERVER
)
564 fstamp
|= CRYPTO_FLAG_AUTO
;
565 if (!(fstamp
& CRYPTO_FLAG_TAI
))
566 fstamp
|= CRYPTO_FLAG_LEAP
;
567 RAND_bytes((u_char
*)&peer
->hcookie
, 4);
568 peer
->crypto
= fstamp
;
570 if (peer
->subject
!= NULL
)
572 peer
->subject
= emalloc(vallen
+ 1);
573 memcpy(peer
->subject
, ep
->pkt
, vallen
);
574 peer
->subject
[vallen
] = '\0';
575 if (peer
->issuer
!= NULL
)
577 peer
->issuer
= emalloc(vallen
+ 1);
578 strcpy(peer
->issuer
, peer
->subject
);
579 snprintf(statstr
, NTP_MAXSTRLEN
,
580 "assoc %d %d host %s %s", peer
->associd
,
581 peer
->assoc
, peer
->subject
,
583 record_crypto_stats(&peer
->srcadr
, statstr
);
586 printf("crypto_recv: %s\n", statstr
);
591 * Decode X509 certificate in ASN.1 format and extract
592 * the data containing, among other things, subject
593 * name and public key. In the default identification
594 * scheme, the certificate trail is followed to a self
595 * signed trusted certificate.
597 case CRYPTO_CERT
| CRYPTO_RESP
:
600 * Discard the message if empty or invalid.
605 if ((rval
= crypto_verify(ep
, NULL
, peer
)) !=
610 * Scan the certificate list to delete old
611 * versions and link the newest version first on
612 * the list. Then, verify the signature. If the
613 * certificate is bad or missing, just ignore
616 if ((xinfo
= cert_install(ep
, peer
)) == NULL
) {
620 if ((rval
= cert_hike(peer
, xinfo
)) != XEVNT_OK
)
624 * We plug in the public key and lifetime from
625 * the first certificate received. However, note
626 * that this certificate might not be signed by
627 * the server, so we can't check the
628 * signature/digest NID.
630 if (peer
->pkey
== NULL
) {
631 ptr
= (u_char
*)xinfo
->cert
.ptr
;
632 cert
= d2i_X509(NULL
, &ptr
,
633 ntohl(xinfo
->cert
.vallen
));
634 peer
->pkey
= X509_get_pubkey(cert
);
637 peer
->flash
&= ~TEST8
;
639 snprintf(statstr
, NTP_MAXSTRLEN
,
640 "cert %s %s 0x%x %s (%u) fs %u",
641 xinfo
->subject
, xinfo
->issuer
, xinfo
->flags
,
642 OBJ_nid2ln(temp32
), temp32
,
644 record_crypto_stats(&peer
->srcadr
, statstr
);
647 printf("crypto_recv: %s\n", statstr
);
652 * Schnorr (IFF) identity scheme. This scheme is
653 * designed for use with shared secret server group keys
654 * and where the certificate may be generated by a third
655 * party. The client sends a challenge to the server,
656 * which performs a calculation and returns the result.
657 * A positive result is possible only if both client and
658 * server contain the same secret group key.
660 case CRYPTO_IFF
| CRYPTO_RESP
:
663 * Discard the message if invalid.
665 if ((rval
= crypto_verify(ep
, NULL
, peer
)) !=
670 * If the challenge matches the response, the
671 * server public key, signature and identity are
672 * all verified at the same time. The server is
673 * declared trusted, so we skip further
674 * certificate exchanges and move immediately to
675 * the cookie exchange.
677 if ((rval
= crypto_iff(ep
, peer
)) != XEVNT_OK
)
680 peer
->crypto
|= CRYPTO_FLAG_VRFY
;
681 peer
->flash
&= ~TEST8
;
682 snprintf(statstr
, NTP_MAXSTRLEN
, "iff %s fs %u",
683 peer
->issuer
, ntohl(ep
->fstamp
));
684 record_crypto_stats(&peer
->srcadr
, statstr
);
687 printf("crypto_recv: %s\n", statstr
);
692 * Guillou-Quisquater (GQ) identity scheme. This scheme
693 * is designed for use with public certificates carrying
694 * the GQ public key in an extension field. The client
695 * sends a challenge to the server, which performs a
696 * calculation and returns the result. A positive result
697 * is possible only if both client and server contain
698 * the same group key and the server has the matching GQ
701 case CRYPTO_GQ
| CRYPTO_RESP
:
704 * Discard the message if invalid
706 if ((rval
= crypto_verify(ep
, NULL
, peer
)) !=
711 * If the challenge matches the response, the
712 * server public key, signature and identity are
713 * all verified at the same time. The server is
714 * declared trusted, so we skip further
715 * certificate exchanges and move immediately to
716 * the cookie exchange.
718 if ((rval
= crypto_gq(ep
, peer
)) != XEVNT_OK
)
721 peer
->crypto
|= CRYPTO_FLAG_VRFY
;
722 peer
->flash
&= ~TEST8
;
723 snprintf(statstr
, NTP_MAXSTRLEN
, "gq %s fs %u",
724 peer
->issuer
, ntohl(ep
->fstamp
));
725 record_crypto_stats(&peer
->srcadr
, statstr
);
728 printf("crypto_recv: %s\n", statstr
);
733 * Mu-Varadharajan (MV) identity scheme. This scheme is
734 * designed for use with three levels of trust, trusted
735 * host, server and client. The trusted host key is
736 * opaque to servers and clients; the server keys are
737 * opaque to clients and each client key is different.
738 * Client keys can be revoked without requiring new key
741 case CRYPTO_MV
| CRYPTO_RESP
:
744 * Discard the message if invalid.
746 if ((rval
= crypto_verify(ep
, NULL
, peer
)) !=
751 * If the challenge matches the response, the
752 * server public key, signature and identity are
753 * all verified at the same time. The server is
754 * declared trusted, so we skip further
755 * certificate exchanges and move immediately to
756 * the cookie exchange.
758 if ((rval
= crypto_mv(ep
, peer
)) != XEVNT_OK
)
761 peer
->crypto
|= CRYPTO_FLAG_VRFY
;
762 peer
->flash
&= ~TEST8
;
763 snprintf(statstr
, NTP_MAXSTRLEN
, "mv %s fs %u",
764 peer
->issuer
, ntohl(ep
->fstamp
));
765 record_crypto_stats(&peer
->srcadr
, statstr
);
768 printf("crypto_recv: %s\n", statstr
);
774 * Cookie response in client and symmetric modes. If the
775 * cookie bit is set, the working cookie is the EXOR of
776 * the current and new values.
778 case CRYPTO_COOK
| CRYPTO_RESP
:
781 * Discard the message if invalid or signature
782 * not verified with respect to the cookie
785 if ((rval
= crypto_verify(ep
, &peer
->cookval
,
790 * Decrypt the cookie, hunting all the time for
793 if (vallen
== (u_int
)EVP_PKEY_size(host_pkey
)) {
794 if (RSA_private_decrypt(vallen
,
798 RSA_PKCS1_OAEP_PADDING
) <= 0) {
802 cookie
= ntohl(temp32
);
810 * Install cookie values and light the cookie
811 * bit. If this is not broadcast client mode, we
815 if (hismode
== MODE_ACTIVE
|| hismode
==
817 peer
->pcookie
= peer
->hcookie
^ cookie
;
819 peer
->pcookie
= cookie
;
820 peer
->crypto
|= CRYPTO_FLAG_COOK
;
821 peer
->flash
&= ~TEST8
;
822 snprintf(statstr
, NTP_MAXSTRLEN
,
823 "cook %x ts %u fs %u", peer
->pcookie
,
824 ntohl(ep
->tstamp
), ntohl(ep
->fstamp
));
825 record_crypto_stats(&peer
->srcadr
, statstr
);
828 printf("crypto_recv: %s\n", statstr
);
833 * Install autokey values in broadcast client and
834 * symmetric modes. We have to do this every time the
835 * sever/peer cookie changes or a new keylist is
836 * rolled. Ordinarily, this is automatic as this message
837 * is piggybacked on the first NTP packet sent upon
838 * either of these events. Note that a broadcast client
839 * or symmetric peer can receive this response without a
842 case CRYPTO_AUTO
| CRYPTO_RESP
:
845 * Discard the message if invalid or signature
846 * not verified with respect to the receive
849 if ((rval
= crypto_verify(ep
, &peer
->recval
,
854 * Discard the message if a broadcast client and
855 * the association ID does not match. This might
856 * happen if a broacast server restarts the
857 * protocol. A protocol restart will occur at
858 * the next ASSOC message.
860 if (peer
->cast_flags
& MDF_BCLNT
&&
861 peer
->assoc
!= associd
)
865 * Install autokey values and light the
866 * autokey bit. This is not hard.
871 if (peer
->recval
.ptr
== NULL
)
873 emalloc(sizeof(struct autokey
));
874 bp
= (struct autokey
*)peer
->recval
.ptr
;
875 peer
->recval
.tstamp
= ep
->tstamp
;
876 peer
->recval
.fstamp
= ep
->fstamp
;
877 ap
= (struct autokey
*)ep
->pkt
;
878 bp
->seq
= ntohl(ap
->seq
);
879 bp
->key
= ntohl(ap
->key
);
880 peer
->pkeyid
= bp
->key
;
881 peer
->crypto
|= CRYPTO_FLAG_AUTO
;
882 peer
->flash
&= ~TEST8
;
883 snprintf(statstr
, NTP_MAXSTRLEN
,
884 "auto seq %d key %x ts %u fs %u", bp
->seq
,
885 bp
->key
, ntohl(ep
->tstamp
),
887 record_crypto_stats(&peer
->srcadr
, statstr
);
890 printf("crypto_recv: %s\n", statstr
);
895 * X509 certificate sign response. Validate the
896 * certificate signed by the server and install. Later
897 * this can be provided to clients of this server in
898 * lieu of the self signed certificate in order to
899 * validate the public key.
901 case CRYPTO_SIGN
| CRYPTO_RESP
:
904 * Discard the message if invalid.
906 if ((rval
= crypto_verify(ep
, NULL
, peer
)) !=
911 * Scan the certificate list to delete old
912 * versions and link the newest version first on
915 if ((xinfo
= cert_install(ep
, peer
)) == NULL
) {
919 peer
->crypto
|= CRYPTO_FLAG_SIGN
;
920 peer
->flash
&= ~TEST8
;
922 snprintf(statstr
, NTP_MAXSTRLEN
,
923 "sign %s %s 0x%x %s (%u) fs %u",
924 xinfo
->subject
, xinfo
->issuer
, xinfo
->flags
,
925 OBJ_nid2ln(temp32
), temp32
,
927 record_crypto_stats(&peer
->srcadr
, statstr
);
930 printf("crypto_recv: %s\n", statstr
);
935 * Install leapseconds values. While the leapsecond
936 * values epoch, TAI offset and values expiration epoch
937 * are retained, only the current TAI offset is provided
938 * via the kernel to other applications.
940 case CRYPTO_LEAP
| CRYPTO_RESP
:
943 * Discard the message if invalid. We can't
944 * compare the value timestamps here, as they
945 * can be updated by different servers.
947 if ((rval
= crypto_verify(ep
, NULL
, peer
)) !=
952 * If the packet leap values are more recent
953 * than the stored ones, install the new leap
954 * values and recompute the signatures.
956 if (ntohl(ep
->pkt
[2]) > leap_expire
) {
957 char tbuf
[80], str1
[20], str2
[20];
959 tai_leap
.tstamp
= ep
->tstamp
;
960 tai_leap
.fstamp
= ep
->fstamp
;
961 tai_leap
.vallen
= ep
->vallen
;
962 leap_tai
= ntohl(ep
->pkt
[0]);
963 leap_sec
= ntohl(ep
->pkt
[1]);
964 leap_expire
= ntohl(ep
->pkt
[2]);
966 strcpy(str1
, fstostr(leap_sec
));
967 strcpy(str2
, fstostr(leap_expire
));
968 snprintf(tbuf
, sizeof(tbuf
),
969 "%d leap %s expire %s", leap_tai
, str1
,
971 report_event(EVNT_TAI
, peer
, tbuf
);
973 peer
->crypto
|= CRYPTO_FLAG_LEAP
;
974 peer
->flash
&= ~TEST8
;
975 snprintf(statstr
, NTP_MAXSTRLEN
,
976 "leap TAI offset %d at %u expire %u fs %u",
977 ntohl(ep
->pkt
[0]), ntohl(ep
->pkt
[1]),
978 ntohl(ep
->pkt
[2]), ntohl(ep
->fstamp
));
979 record_crypto_stats(&peer
->srcadr
, statstr
);
982 printf("crypto_recv: %s\n", statstr
);
987 * We come here in symmetric modes for miscellaneous
988 * commands that have value fields but are processed on
989 * the transmit side. All we need do here is check for
990 * valid field length. Note that ASSOC is handled
999 if (len
< VALUE_LEN
) {
1006 * We come here in symmetric modes for requests
1007 * requiring a response (above plus AUTO and LEAP) and
1008 * for responses. If a request, save the extension field
1009 * for later; invalid requests will be caught on the
1010 * transmit side. If an error or invalid response,
1011 * declare a protocol error.
1014 if (code
& (CRYPTO_RESP
| CRYPTO_ERROR
)) {
1016 } else if (peer
->cmmd
== NULL
) {
1018 memcpy(fp
, ep
, len
);
1024 * The first error found terminates the extension field
1025 * scan and we return the laundry to the caller.
1027 if (rval
!= XEVNT_OK
) {
1028 snprintf(statstr
, NTP_MAXSTRLEN
,
1029 "%04x %d %02x %s", htonl(ep
->opcode
),
1030 associd
, rval
, eventstr(rval
));
1031 record_crypto_stats(&peer
->srcadr
, statstr
);
1034 printf("crypto_recv: %s\n", statstr
);
1038 authlen
+= (len
+ 3) / 4 * 4;
1045 * crypto_xmit - construct extension fields
1047 * This routine is called both when an association is configured and
1048 * when one is not. The only case where this matters is to retrieve the
1049 * autokey information, in which case the caller has to provide the
1050 * association ID to match the association.
1052 * Side effect: update the packet offset.
1056 * XEVNT_CRT bad or missing certificate
1057 * XEVNT_ERR protocol error
1058 * XEVNT_LEN bad field format or length
1059 * XEVNT_PER host certificate expired
1063 struct peer
*peer
, /* peer structure pointer */
1064 struct pkt
*xpkt
, /* transmit packet pointer */
1065 struct recvbuf
*rbufp
, /* receive buffer pointer */
1066 int start
, /* offset to extension field */
1067 struct exten
*ep
, /* extension pointer */
1068 keyid_t cookie
/* session cookie */
1071 struct exten
*fp
; /* extension pointers */
1072 struct cert_info
*cp
, *xp
, *yp
; /* cert info/value pointer */
1073 sockaddr_u
*srcadr_sin
; /* source address */
1074 u_int32
*pkt
; /* packet pointer */
1075 u_int opcode
; /* extension field opcode */
1076 char certname
[MAXHOSTNAME
+ 1]; /* subject name buffer */
1077 char statstr
[NTP_MAXSTRLEN
]; /* statistics for filegen */
1087 * Generate the requested extension field request code, length
1088 * and association ID. If this is a response and the host is not
1089 * synchronized, light the error bit and go home.
1091 pkt
= (u_int32
*)xpkt
+ start
/ 4;
1092 fp
= (struct exten
*)pkt
;
1093 opcode
= ntohl(ep
->opcode
);
1095 srcadr_sin
= &peer
->srcadr
;
1096 if (!(opcode
& CRYPTO_RESP
))
1097 peer
->opcode
= ep
->opcode
;
1099 srcadr_sin
= &rbufp
->recv_srcadr
;
1101 associd
= (associd_t
) ntohl(ep
->associd
);
1103 fp
->opcode
= htonl((opcode
& 0xffff0000) | len
);
1104 fp
->associd
= ep
->associd
;
1106 tstamp
= crypto_time();
1107 switch (opcode
& 0xffff0000) {
1110 * Send association request and response with status word and
1111 * host name. Note, this message is not signed and the filestamp
1112 * contains only the status word.
1115 case CRYPTO_ASSOC
| CRYPTO_RESP
:
1116 len
= crypto_send(fp
, &hostval
, start
);
1117 fp
->fstamp
= htonl(crypto_flags
);
1121 * Send certificate request. Use the values from the extension
1125 memset(&vtemp
, 0, sizeof(vtemp
));
1126 vtemp
.tstamp
= ep
->tstamp
;
1127 vtemp
.fstamp
= ep
->fstamp
;
1128 vtemp
.vallen
= ep
->vallen
;
1129 vtemp
.ptr
= (u_char
*)ep
->pkt
;
1130 len
= crypto_send(fp
, &vtemp
, start
);
1134 * Send sign request. Use the host certificate, which is self-
1135 * signed and may or may not be trusted.
1138 if (tstamp
< cert_host
->first
|| tstamp
>
1142 len
= crypto_send(fp
, &cert_host
->cert
, start
);
1146 * Send certificate response. Use the name in the extension
1147 * field to find the certificate in the cache. If the request
1148 * contains no subject name, assume the name of this host. This
1149 * is for backwards compatibility. Private certificates are
1152 * There may be several certificates matching the request. First
1153 * choice is a self-signed trusted certificate; second choice is
1154 * any certificate signed by another host. There is no third
1157 case CRYPTO_CERT
| CRYPTO_RESP
:
1158 vallen
= ntohl(ep
->vallen
);
1159 if (vallen
== 0 || vallen
> MAXHOSTNAME
) {
1164 memcpy(certname
, ep
->pkt
, vallen
);
1165 certname
[vallen
] = '\0';
1169 * Find all public valid certificates with matching
1170 * subject. If a self-signed, trusted certificate is
1171 * found, use that certificate. If not, use the last non
1172 * self-signed certificate.
1175 for (cp
= cinfo
; cp
!= NULL
; cp
= cp
->link
) {
1176 if (cp
->flags
& (CERT_PRIV
| CERT_ERROR
))
1179 if (strcmp(certname
, cp
->subject
) != 0)
1182 if (strcmp(certname
, cp
->issuer
) != 0)
1184 else if (cp
->flags
& CERT_TRUST
)
1190 * Be careful who you trust. If the certificate is not
1191 * found, return an empty response. Note that we dont
1192 * enforce lifetimes here.
1194 * The timestamp and filestamp are taken from the
1195 * certificate value structure. For all certificates the
1196 * timestamp is the latest signature update time. For
1197 * host and imported certificates the filestamp is the
1198 * creation epoch. For signed certificates the filestamp
1199 * is the creation epoch of the trusted certificate at
1200 * the root of the certificate trail. In principle, this
1201 * allows strong checking for signature masquerade.
1211 len
= crypto_send(fp
, &xp
->cert
, start
);
1215 * Send challenge in Schnorr (IFF) identity scheme.
1219 break; /* hack attack */
1221 if ((rval
= crypto_alice(peer
, &vtemp
)) == XEVNT_OK
) {
1222 len
= crypto_send(fp
, &vtemp
, start
);
1228 * Send response in Schnorr (IFF) identity scheme.
1230 case CRYPTO_IFF
| CRYPTO_RESP
:
1231 if ((rval
= crypto_bob(ep
, &vtemp
)) == XEVNT_OK
) {
1232 len
= crypto_send(fp
, &vtemp
, start
);
1238 * Send challenge in Guillou-Quisquater (GQ) identity scheme.
1242 break; /* hack attack */
1244 if ((rval
= crypto_alice2(peer
, &vtemp
)) == XEVNT_OK
) {
1245 len
= crypto_send(fp
, &vtemp
, start
);
1251 * Send response in Guillou-Quisquater (GQ) identity scheme.
1253 case CRYPTO_GQ
| CRYPTO_RESP
:
1254 if ((rval
= crypto_bob2(ep
, &vtemp
)) == XEVNT_OK
) {
1255 len
= crypto_send(fp
, &vtemp
, start
);
1261 * Send challenge in MV identity scheme.
1265 break; /* hack attack */
1267 if ((rval
= crypto_alice3(peer
, &vtemp
)) == XEVNT_OK
) {
1268 len
= crypto_send(fp
, &vtemp
, start
);
1274 * Send response in MV identity scheme.
1276 case CRYPTO_MV
| CRYPTO_RESP
:
1277 if ((rval
= crypto_bob3(ep
, &vtemp
)) == XEVNT_OK
) {
1278 len
= crypto_send(fp
, &vtemp
, start
);
1284 * Send certificate sign response. The integrity of the request
1285 * certificate has already been verified on the receive side.
1286 * Sign the response using the local server key. Use the
1287 * filestamp from the request and use the timestamp as the
1288 * current time. Light the error bit if the certificate is
1289 * invalid or contains an unverified signature.
1291 case CRYPTO_SIGN
| CRYPTO_RESP
:
1292 if ((rval
= cert_sign(ep
, &vtemp
)) == XEVNT_OK
) {
1293 len
= crypto_send(fp
, &vtemp
, start
);
1299 * Send public key and signature. Use the values from the public
1303 len
= crypto_send(fp
, &pubkey
, start
);
1307 * Encrypt and send cookie and signature. Light the error bit if
1308 * anything goes wrong.
1310 case CRYPTO_COOK
| CRYPTO_RESP
:
1311 if ((opcode
& 0xffff) < VALUE_LEN
) {
1318 tcookie
= peer
->hcookie
;
1319 if ((rval
= crypto_encrypt(ep
, &vtemp
, &tcookie
)) ==
1321 len
= crypto_send(fp
, &vtemp
, start
);
1327 * Find peer and send autokey data and signature in broadcast
1328 * server and symmetric modes. Use the values in the autokey
1329 * structure. If no association is found, either the server has
1330 * restarted with new associations or some perp has replayed an
1331 * old message, in which case light the error bit.
1333 case CRYPTO_AUTO
| CRYPTO_RESP
:
1335 if ((peer
= findpeerbyassoc(associd
)) == NULL
) {
1340 peer
->flags
&= ~FLAG_ASSOC
;
1341 len
= crypto_send(fp
, &peer
->sndval
, start
);
1345 * Send leapseconds values and signature. Use the values from
1346 * the tai structure. If no table has been loaded, just send an
1349 case CRYPTO_LEAP
| CRYPTO_RESP
:
1350 len
= crypto_send(fp
, &tai_leap
, start
);
1354 * Default - Send a valid command for unknown requests; send
1355 * an error response for unknown resonses.
1358 if (opcode
& CRYPTO_RESP
)
1363 * In case of error, flame the log. If a request, toss the
1364 * puppy; if a response, return so the sender can flame, too.
1366 if (rval
!= XEVNT_OK
) {
1369 uint32
= CRYPTO_ERROR
;
1371 fp
->opcode
|= htonl(uint32
);
1372 snprintf(statstr
, NTP_MAXSTRLEN
,
1373 "%04x %d %02x %s", opcode
, associd
, rval
,
1375 record_crypto_stats(srcadr_sin
, statstr
);
1378 printf("crypto_xmit: %s\n", statstr
);
1380 if (!(opcode
& CRYPTO_RESP
))
1386 "crypto_xmit: flags 0x%x offset %d len %d code 0x%x associd %d\n",
1387 crypto_flags
, start
, len
, opcode
>> 16, associd
);
1394 * crypto_verify - verify the extension field value and signature
1398 * XEVNT_ERR protocol error
1399 * XEVNT_FSP bad filestamp
1400 * XEVNT_LEN bad field format or length
1401 * XEVNT_PUB bad or missing public key
1402 * XEVNT_SGL bad signature length
1403 * XEVNT_SIG signature not verified
1404 * XEVNT_TSP bad timestamp
1408 struct exten
*ep
, /* extension pointer */
1409 struct value
*vp
, /* value pointer */
1410 struct peer
*peer
/* peer structure pointer */
1413 EVP_PKEY
*pkey
; /* server public key */
1414 EVP_MD_CTX ctx
; /* signature context */
1415 tstamp_t tstamp
, tstamp1
= 0; /* timestamp */
1416 tstamp_t fstamp
, fstamp1
= 0; /* filestamp */
1417 u_int vallen
; /* value length */
1418 u_int siglen
; /* signature length */
1423 * We are extremely parannoyed. We require valid opcode, length,
1424 * association ID, timestamp, filestamp, public key, digest,
1425 * signature length and signature, where relevant. Note that
1426 * preliminary length checks are done in the main loop.
1428 len
= ntohl(ep
->opcode
) & 0x0000ffff;
1429 opcode
= ntohl(ep
->opcode
) & 0xffff0000;
1432 * Check for valid value header, association ID and extension
1433 * field length. Remember, it is not an error to receive an
1434 * unsolicited response; however, the response ID must match
1435 * the association ID.
1437 if (opcode
& CRYPTO_ERROR
)
1440 if (len
< VALUE_LEN
)
1443 if (opcode
== (CRYPTO_AUTO
| CRYPTO_RESP
) && (peer
->pmode
==
1444 MODE_BROADCAST
|| (peer
->cast_flags
& MDF_BCLNT
))) {
1445 if (ntohl(ep
->associd
) != peer
->assoc
)
1448 if (ntohl(ep
->associd
) != peer
->associd
)
1453 * We have a valid value header. Check for valid value and
1454 * signature field lengths. The extension field length must be
1455 * long enough to contain the value header, value and signature.
1456 * Note both the value and signature field lengths are rounded
1457 * up to the next word (4 octets).
1459 vallen
= ntohl(ep
->vallen
);
1463 i
= (vallen
+ 3) / 4;
1464 siglen
= ntohl(ep
->pkt
[i
++]);
1465 if (len
< VALUE_LEN
+ ((vallen
+ 3) / 4) * 4 + ((siglen
+ 3) /
1470 * Check for valid timestamp and filestamp. If the timestamp is
1471 * zero, the sender is not synchronized and signatures are
1472 * not possible. If nonzero the timestamp must not precede the
1473 * filestamp. The timestamp and filestamp must not precede the
1474 * corresponding values in the value structure, if present.
1476 tstamp
= ntohl(ep
->tstamp
);
1477 fstamp
= ntohl(ep
->fstamp
);
1481 if (tstamp
< fstamp
)
1485 tstamp1
= ntohl(vp
->tstamp
);
1486 fstamp1
= ntohl(vp
->fstamp
);
1487 if (tstamp1
!= 0 && fstamp1
!= 0) {
1488 if (tstamp
< tstamp1
)
1491 if ((tstamp
< fstamp1
|| fstamp
< fstamp1
))
1497 * At the time the certificate message is validated, the public
1498 * key in the message is not available. Thus, don't try to
1499 * verify the signature.
1501 if (opcode
== (CRYPTO_CERT
| CRYPTO_RESP
))
1505 * Check for valid signature length, public key and digest
1508 if (crypto_flags
& peer
->crypto
& CRYPTO_FLAG_PRIV
)
1512 if (siglen
== 0 || pkey
== NULL
|| peer
->digest
== NULL
)
1515 if (siglen
!= (u_int
)EVP_PKEY_size(pkey
))
1519 * Darn, I thought we would never get here. Verify the
1520 * signature. If the identity exchange is verified, light the
1521 * proventic bit. What a relief.
1523 EVP_VerifyInit(&ctx
, peer
->digest
);
1524 EVP_VerifyUpdate(&ctx
, (u_char
*)&ep
->tstamp
, vallen
+ 12);
1525 if (EVP_VerifyFinal(&ctx
, (u_char
*)&ep
->pkt
[i
], siglen
,
1529 if (peer
->crypto
& CRYPTO_FLAG_VRFY
)
1530 peer
->crypto
|= CRYPTO_FLAG_PROV
;
1536 * crypto_encrypt - construct encrypted cookie and signature from
1537 * extension field and cookie
1541 * XEVNT_CKY bad or missing cookie
1542 * XEVNT_PUB bad or missing public key
1546 struct exten
*ep
, /* extension pointer */
1547 struct value
*vp
, /* value pointer */
1548 keyid_t
*cookie
/* server cookie */
1551 EVP_PKEY
*pkey
; /* public key */
1552 EVP_MD_CTX ctx
; /* signature context */
1553 tstamp_t tstamp
; /* NTP timestamp */
1560 * Extract the public key from the request.
1562 len
= ntohl(ep
->vallen
);
1563 ptr
= (u_char
*)ep
->pkt
;
1564 pkey
= d2i_PublicKey(EVP_PKEY_RSA
, NULL
, &ptr
, len
);
1566 msyslog(LOG_ERR
, "crypto_encrypt: %s",
1567 ERR_error_string(ERR_get_error(), NULL
));
1572 * Encrypt the cookie, encode in ASN.1 and sign.
1574 memset(vp
, 0, sizeof(struct value
));
1575 tstamp
= crypto_time();
1576 vp
->tstamp
= htonl(tstamp
);
1577 vp
->fstamp
= hostval
.tstamp
;
1578 len
= EVP_PKEY_size(pkey
);
1579 vp
->vallen
= htonl(len
);
1580 vp
->ptr
= emalloc(len
);
1582 temp32
= htonl(*cookie
);
1583 if (RSA_public_encrypt(4, (const u_char
*)&temp32
, sptr
,
1584 pkey
->pkey
.rsa
, RSA_PKCS1_OAEP_PADDING
) <= 0) {
1585 msyslog(LOG_ERR
, "crypto_encrypt: %s",
1586 ERR_error_string(ERR_get_error(), NULL
));
1588 EVP_PKEY_free(pkey
);
1591 EVP_PKEY_free(pkey
);
1595 vp
->sig
= emalloc(sign_siglen
);
1596 EVP_SignInit(&ctx
, sign_digest
);
1597 EVP_SignUpdate(&ctx
, (u_char
*)&vp
->tstamp
, 12);
1598 EVP_SignUpdate(&ctx
, vp
->ptr
, len
);
1599 if (EVP_SignFinal(&ctx
, vp
->sig
, &len
, sign_pkey
))
1600 vp
->siglen
= htonl(sign_siglen
);
1606 * crypto_ident - construct extension field for identity scheme
1608 * This routine determines which identity scheme is in use and
1609 * constructs an extension field for that scheme.
1612 * CRYTPO_IFF IFF scheme
1613 * CRYPTO_GQ GQ scheme
1614 * CRYPTO_MV MV scheme
1615 * CRYPTO_NULL no available scheme
1619 struct peer
*peer
/* peer structure pointer */
1622 char filename
[MAXFILENAME
];
1625 * We come here after the group trusted host has been found; its
1626 * name defines the group name. Search the key cache for all
1627 * keys matching the same group name in order IFF, GQ and MV.
1628 * Use the first one available.
1630 if (peer
->crypto
& CRYPTO_FLAG_IFF
) {
1631 snprintf(filename
, MAXFILENAME
, "ntpkey_iffpar_%s",
1633 peer
->ident_pkey
= crypto_key(filename
, NULL
,
1635 if (peer
->ident_pkey
!= NULL
)
1636 return (CRYPTO_IFF
);
1638 if (peer
->crypto
& CRYPTO_FLAG_GQ
) {
1639 snprintf(filename
, MAXFILENAME
, "ntpkey_gqpar_%s",
1641 peer
->ident_pkey
= crypto_key(filename
, NULL
,
1643 if (peer
->ident_pkey
!= NULL
)
1646 if (peer
->crypto
& CRYPTO_FLAG_MV
) {
1647 snprintf(filename
, MAXFILENAME
, "ntpkey_mvpar_%s",
1649 peer
->ident_pkey
= crypto_key(filename
, NULL
,
1651 if (peer
->ident_pkey
!= NULL
)
1655 "crypto_ident: no identity parameters found for group %s",
1657 return (CRYPTO_NULL
);
1662 * crypto_args - construct extension field from arguments
1664 * This routine creates an extension field with current timestamps and
1665 * specified opcode, association ID and optional string. Note that the
1666 * extension field is created here, but freed after the crypto_xmit()
1667 * call in the protocol module.
1669 * Returns extension field pointer (no errors)
1673 struct peer
*peer
, /* peer structure pointer */
1674 u_int opcode
, /* operation code */
1675 associd_t associd
, /* association ID */
1676 char *str
/* argument string */
1679 tstamp_t tstamp
; /* NTP timestamp */
1680 struct exten
*ep
; /* extension field pointer */
1681 u_int len
; /* extension field length */
1683 tstamp
= crypto_time();
1684 len
= sizeof(struct exten
);
1692 ep
->opcode
= htonl(opcode
+ len
);
1693 ep
->associd
= htonl(associd
);
1694 ep
->tstamp
= htonl(tstamp
);
1695 ep
->fstamp
= hostval
.tstamp
;
1698 ep
->vallen
= htonl(strlen(str
));
1699 memcpy((char *)ep
->pkt
, str
, strlen(str
));
1706 * crypto_send - construct extension field from value components
1708 * The value and signature fields are zero-padded to a word boundary.
1709 * Note: it is not polite to send a nonempty signature with zero
1710 * timestamp or a nonzero timestamp with an empty signature, but those
1711 * rules are not enforced here.
1715 struct exten
*ep
, /* extension field pointer */
1716 struct value
*vp
, /* value pointer */
1717 int start
/* buffer offset */
1720 u_int len
, vallen
, siglen
, opcode
;
1724 * Calculate extension field length and check for buffer
1725 * overflow. Leave room for the MAC.
1728 vallen
= ntohl(vp
->vallen
);
1729 len
+= ((vallen
+ 3) / 4 + 1) * 4;
1730 siglen
= ntohl(vp
->siglen
);
1731 len
+= ((siglen
+ 3) / 4 + 1) * 4;
1732 if (start
+ len
> sizeof(struct pkt
) - MAX_MAC_LEN
)
1738 ep
->tstamp
= vp
->tstamp
;
1739 ep
->fstamp
= vp
->fstamp
;
1740 ep
->vallen
= vp
->vallen
;
1743 * Copy value. If the data field is empty or zero length,
1744 * encode an empty value with length zero.
1747 if (vallen
> 0 && vp
->ptr
!= NULL
) {
1750 ep
->pkt
[i
+ j
++] = 0;
1751 memcpy(&ep
->pkt
[i
], vp
->ptr
, vallen
);
1756 * Copy signature. If the signature field is empty or zero
1757 * length, encode an empty signature with length zero.
1759 ep
->pkt
[i
++] = vp
->siglen
;
1760 if (siglen
> 0 && vp
->sig
!= NULL
) {
1763 ep
->pkt
[i
+ j
++] = 0;
1764 memcpy(&ep
->pkt
[i
], vp
->sig
, siglen
);
1767 opcode
= ntohl(ep
->opcode
);
1768 ep
->opcode
= htonl((opcode
& 0xffff0000) | len
);
1774 * crypto_update - compute new public value and sign extension fields
1776 * This routine runs periodically, like once a day, and when something
1777 * changes. It updates the timestamps on three value structures and one
1778 * value structure list, then signs all the structures:
1780 * hostval host name (not signed)
1782 * cinfo certificate info/value list
1783 * tai_leap leap values
1785 * Filestamps are proventic data, so this routine runs only when the
1786 * host is synchronized to a proventicated source. Thus, the timestamp
1787 * is proventic and can be used to deflect clogging attacks.
1789 * Returns void (no errors)
1794 EVP_MD_CTX ctx
; /* message digest context */
1795 struct cert_info
*cp
; /* certificate info/value */
1796 char statstr
[NTP_MAXSTRLEN
]; /* statistics for filegen */
1800 hostval
.tstamp
= htonl(crypto_time());
1801 if (hostval
.tstamp
== 0)
1806 * Sign public key and timestamps. The filestamp is derived from
1807 * the host key file extension from wherever the file was
1810 if (pubkey
.vallen
!= 0) {
1811 pubkey
.tstamp
= hostval
.tstamp
;
1813 if (pubkey
.sig
== NULL
)
1814 pubkey
.sig
= emalloc(sign_siglen
);
1815 EVP_SignInit(&ctx
, sign_digest
);
1816 EVP_SignUpdate(&ctx
, (u_char
*)&pubkey
, 12);
1817 EVP_SignUpdate(&ctx
, pubkey
.ptr
, ntohl(pubkey
.vallen
));
1818 if (EVP_SignFinal(&ctx
, pubkey
.sig
, &len
, sign_pkey
))
1819 pubkey
.siglen
= htonl(sign_siglen
);
1823 * Sign certificates and timestamps. The filestamp is derived
1824 * from the certificate file extension from wherever the file
1825 * was generated. Note we do not throw expired certificates
1826 * away; they may have signed younger ones.
1828 for (cp
= cinfo
; cp
!= NULL
; cp
= cp
->link
) {
1829 cp
->cert
.tstamp
= hostval
.tstamp
;
1830 cp
->cert
.siglen
= 0;
1831 if (cp
->cert
.sig
== NULL
)
1832 cp
->cert
.sig
= emalloc(sign_siglen
);
1833 EVP_SignInit(&ctx
, sign_digest
);
1834 EVP_SignUpdate(&ctx
, (u_char
*)&cp
->cert
, 12);
1835 EVP_SignUpdate(&ctx
, cp
->cert
.ptr
,
1836 ntohl(cp
->cert
.vallen
));
1837 if (EVP_SignFinal(&ctx
, cp
->cert
.sig
, &len
, sign_pkey
))
1838 cp
->cert
.siglen
= htonl(sign_siglen
);
1842 * Sign leapseconds values and timestamps. Note it is not an
1843 * error to return null values.
1845 tai_leap
.tstamp
= hostval
.tstamp
;
1846 tai_leap
.fstamp
= hostval
.fstamp
;
1847 len
= 3 * sizeof(u_int32
);
1848 if (tai_leap
.ptr
== NULL
)
1849 tai_leap
.ptr
= emalloc(len
);
1850 tai_leap
.vallen
= htonl(len
);
1851 ptr
= (u_int32
*)tai_leap
.ptr
;
1852 ptr
[0] = htonl(leap_tai
);
1853 ptr
[1] = htonl(leap_sec
);
1854 ptr
[2] = htonl(leap_expire
);
1855 if (tai_leap
.sig
== NULL
)
1856 tai_leap
.sig
= emalloc(sign_siglen
);
1857 EVP_SignInit(&ctx
, sign_digest
);
1858 EVP_SignUpdate(&ctx
, (u_char
*)&tai_leap
, 12);
1859 EVP_SignUpdate(&ctx
, tai_leap
.ptr
, len
);
1860 if (EVP_SignFinal(&ctx
, tai_leap
.sig
, &len
, sign_pkey
))
1861 tai_leap
.siglen
= htonl(sign_siglen
);
1863 crypto_flags
|= CRYPTO_FLAG_TAI
;
1864 snprintf(statstr
, NTP_MAXSTRLEN
, "signature update ts %u",
1865 ntohl(hostval
.tstamp
));
1866 record_crypto_stats(NULL
, statstr
);
1869 printf("crypto_update: %s\n", statstr
);
1875 * value_free - free value structure components.
1877 * Returns void (no errors)
1881 struct value
*vp
/* value structure */
1884 if (vp
->ptr
!= NULL
)
1886 if (vp
->sig
!= NULL
)
1888 memset(vp
, 0, sizeof(struct value
));
1893 * crypto_time - returns current NTP time.
1895 * Returns NTP seconds if in synch, 0 otherwise
1900 l_fp tstamp
; /* NTP time */
1903 if (sys_leap
!= LEAP_NOTINSYNC
)
1904 get_systime(&tstamp
);
1905 return (tstamp
.l_ui
);
1910 * asn2ntp - convert ASN1_TIME time structure to NTP time.
1912 * Returns NTP seconds (no errors)
1916 ASN1_TIME
*asn1time
/* pointer to ASN1_TIME structure */
1919 char *v
; /* pointer to ASN1_TIME string */
1920 struct tm tm
; /* used to convert to NTP time */
1923 * Extract time string YYMMDDHHMMSSZ from ASN1 time structure.
1924 * Note that the YY, MM, DD fields start with one, the HH, MM,
1925 * SS fiels start with zero and the Z character is ignored.
1926 * Also note that years less than 50 map to years greater than
1927 * 100. Dontcha love ASN.1? Better than MIL-188.
1929 v
= (char *)asn1time
->data
;
1930 tm
.tm_year
= (v
[0] - '0') * 10 + v
[1] - '0';
1931 if (tm
.tm_year
< 50)
1933 tm
.tm_mon
= (v
[2] - '0') * 10 + v
[3] - '0' - 1;
1934 tm
.tm_mday
= (v
[4] - '0') * 10 + v
[5] - '0';
1935 tm
.tm_hour
= (v
[6] - '0') * 10 + v
[7] - '0';
1936 tm
.tm_min
= (v
[8] - '0') * 10 + v
[9] - '0';
1937 tm
.tm_sec
= (v
[10] - '0') * 10 + v
[11] - '0';
1941 return ((u_long
)timegm(&tm
) + JAN_1970
);
1946 * bigdig() - compute a BIGNUM MD5 hash of a BIGNUM number.
1948 * Returns void (no errors)
1952 BIGNUM
*bn
, /* BIGNUM * from */
1953 BIGNUM
*bk
/* BIGNUM * to */
1956 EVP_MD_CTX ctx
; /* message digest context */
1957 u_char dgst
[EVP_MAX_MD_SIZE
]; /* message digest */
1958 u_char
*ptr
; /* a BIGNUM as binary string */
1961 len
= BN_num_bytes(bn
);
1964 EVP_DigestInit(&ctx
, EVP_md5());
1965 EVP_DigestUpdate(&ctx
, ptr
, len
);
1966 EVP_DigestFinal(&ctx
, dgst
, &len
);
1967 BN_bin2bn(dgst
, len
, bk
);
1973 ***********************************************************************
1975 * The following routines implement the Schnorr (IFF) identity scheme *
1977 ***********************************************************************
1979 * The Schnorr (IFF) identity scheme is intended for use when
1980 * certificates are generated by some other trusted certificate
1981 * authority and the certificate cannot be used to convey public
1982 * parameters. There are two kinds of files: encrypted server files that
1983 * contain private and public values and nonencrypted client files that
1984 * contain only public values. New generations of server files must be
1985 * securely transmitted to all servers of the group; client files can be
1986 * distributed by any means. The scheme is self contained and
1987 * independent of new generations of host keys, sign keys and
1990 * The IFF values hide in a DSA cuckoo structure which uses the same
1991 * parameters. The values are used by an identity scheme based on DSA
1992 * cryptography and described in Stimson p. 285. The p is a 512-bit
1993 * prime, g a generator of Zp* and q a 160-bit prime that divides p - 1
1994 * and is a qth root of 1 mod p; that is, g^q = 1 mod p. The TA rolls a
1995 * private random group key b (0 < b < q) and public key v = g^b, then
1996 * sends (p, q, g, b) to the servers and (p, q, g, v) to the clients.
1997 * Alice challenges Bob to confirm identity using the protocol described
2002 * The scheme goes like this. Both Alice and Bob have the public primes
2003 * p, q and generator g. The TA gives private key b to Bob and public
2006 * Alice rolls new random challenge r (o < r < q) and sends to Bob in
2007 * the IFF request message. Bob rolls new random k (0 < k < q), then
2008 * computes y = k + b r mod q and x = g^k mod p and sends (y, hash(x))
2009 * to Alice in the response message. Besides making the response
2010 * shorter, the hash makes it effectivey impossible for an intruder to
2011 * solve for b by observing a number of these messages.
2013 * Alice receives the response and computes g^y v^r mod p. After a bit
2014 * of algebra, this simplifies to g^k. If the hash of this result
2015 * matches hash(x), Alice knows that Bob has the group key b. The signed
2016 * response binds this knowledge to Bob's private key and the public key
2017 * previously received in his certificate.
2019 * crypto_alice - construct Alice's challenge in IFF scheme
2023 * XEVNT_ID bad or missing group key
2024 * XEVNT_PUB bad or missing public key
2028 struct peer
*peer
, /* peer pointer */
2029 struct value
*vp
/* value pointer */
2032 DSA
*dsa
; /* IFF parameters */
2033 BN_CTX
*bctx
; /* BIGNUM context */
2034 EVP_MD_CTX ctx
; /* signature context */
2039 * The identity parameters must have correct format and content.
2041 if (peer
->ident_pkey
== NULL
)
2044 if ((dsa
= peer
->ident_pkey
->pkey
->pkey
.dsa
) == NULL
) {
2045 msyslog(LOG_NOTICE
, "crypto_alice: defective key");
2050 * Roll new random r (0 < r < q).
2052 if (peer
->iffval
!= NULL
)
2053 BN_free(peer
->iffval
);
2054 peer
->iffval
= BN_new();
2055 len
= BN_num_bytes(dsa
->q
);
2056 BN_rand(peer
->iffval
, len
* 8, -1, 1); /* r mod q*/
2057 bctx
= BN_CTX_new();
2058 BN_mod(peer
->iffval
, peer
->iffval
, dsa
->q
, bctx
);
2062 * Sign and send to Bob. The filestamp is from the local file.
2064 memset(vp
, 0, sizeof(struct value
));
2065 tstamp
= crypto_time();
2066 vp
->tstamp
= htonl(tstamp
);
2067 vp
->fstamp
= htonl(peer
->ident_pkey
->fstamp
);
2068 vp
->vallen
= htonl(len
);
2069 vp
->ptr
= emalloc(len
);
2070 BN_bn2bin(peer
->iffval
, vp
->ptr
);
2074 vp
->sig
= emalloc(sign_siglen
);
2075 EVP_SignInit(&ctx
, sign_digest
);
2076 EVP_SignUpdate(&ctx
, (u_char
*)&vp
->tstamp
, 12);
2077 EVP_SignUpdate(&ctx
, vp
->ptr
, len
);
2078 if (EVP_SignFinal(&ctx
, vp
->sig
, &len
, sign_pkey
))
2079 vp
->siglen
= htonl(sign_siglen
);
2085 * crypto_bob - construct Bob's response to Alice's challenge
2089 * XEVNT_ERR protocol error
2090 * XEVNT_ID bad or missing group key
2094 struct exten
*ep
, /* extension pointer */
2095 struct value
*vp
/* value pointer */
2098 DSA
*dsa
; /* IFF parameters */
2099 DSA_SIG
*sdsa
; /* DSA signature context fake */
2100 BN_CTX
*bctx
; /* BIGNUM context */
2101 EVP_MD_CTX ctx
; /* signature context */
2102 tstamp_t tstamp
; /* NTP timestamp */
2103 BIGNUM
*bn
, *bk
, *r
;
2108 * If the IFF parameters are not valid, something awful
2109 * happened or we are being tormented.
2111 if (iffkey_info
== NULL
) {
2112 msyslog(LOG_NOTICE
, "crypto_bob: scheme unavailable");
2115 dsa
= iffkey_info
->pkey
->pkey
.dsa
;
2118 * Extract r from the challenge.
2120 len
= ntohl(ep
->vallen
);
2121 if ((r
= BN_bin2bn((u_char
*)ep
->pkt
, len
, NULL
)) == NULL
) {
2122 msyslog(LOG_ERR
, "crypto_bob: %s",
2123 ERR_error_string(ERR_get_error(), NULL
));
2128 * Bob rolls random k (0 < k < q), computes y = k + b r mod q
2129 * and x = g^k mod p, then sends (y, hash(x)) to Alice.
2131 bctx
= BN_CTX_new(); bk
= BN_new(); bn
= BN_new();
2132 sdsa
= DSA_SIG_new();
2133 BN_rand(bk
, len
* 8, -1, 1); /* k */
2134 BN_mod_mul(bn
, dsa
->priv_key
, r
, dsa
->q
, bctx
); /* b r mod q */
2136 BN_mod(bn
, bn
, dsa
->q
, bctx
); /* k + b r mod q */
2137 sdsa
->r
= BN_dup(bn
);
2138 BN_mod_exp(bk
, dsa
->g
, bk
, dsa
->p
, bctx
); /* g^k mod p */
2140 sdsa
->s
= BN_dup(bk
);
2142 BN_free(r
); BN_free(bn
); BN_free(bk
);
2145 DSA_print_fp(stdout
, dsa
, 0);
2149 * Encode the values in ASN.1 and sign. The filestamp is from
2152 len
= i2d_DSA_SIG(sdsa
, NULL
);
2154 msyslog(LOG_ERR
, "crypto_bob: %s",
2155 ERR_error_string(ERR_get_error(), NULL
));
2159 memset(vp
, 0, sizeof(struct value
));
2160 tstamp
= crypto_time();
2161 vp
->tstamp
= htonl(tstamp
);
2162 vp
->fstamp
= htonl(iffkey_info
->fstamp
);
2163 vp
->vallen
= htonl(len
);
2166 i2d_DSA_SIG(sdsa
, &ptr
);
2171 vp
->sig
= emalloc(sign_siglen
);
2172 EVP_SignInit(&ctx
, sign_digest
);
2173 EVP_SignUpdate(&ctx
, (u_char
*)&vp
->tstamp
, 12);
2174 EVP_SignUpdate(&ctx
, vp
->ptr
, len
);
2175 if (EVP_SignFinal(&ctx
, vp
->sig
, &len
, sign_pkey
))
2176 vp
->siglen
= htonl(sign_siglen
);
2182 * crypto_iff - verify Bob's response to Alice's challenge
2186 * XEVNT_FSP bad filestamp
2187 * XEVNT_ID bad or missing group key
2188 * XEVNT_PUB bad or missing public key
2192 struct exten
*ep
, /* extension pointer */
2193 struct peer
*peer
/* peer structure pointer */
2196 DSA
*dsa
; /* IFF parameters */
2197 BN_CTX
*bctx
; /* BIGNUM context */
2198 DSA_SIG
*sdsa
; /* DSA parameters */
2205 * If the IFF parameters are not valid or no challenge was sent,
2206 * something awful happened or we are being tormented.
2208 if (peer
->ident_pkey
== NULL
) {
2209 msyslog(LOG_NOTICE
, "crypto_iff: scheme unavailable");
2212 if (ntohl(ep
->fstamp
) != peer
->ident_pkey
->fstamp
) {
2213 msyslog(LOG_NOTICE
, "crypto_iff: invalid filestamp %u",
2217 if ((dsa
= peer
->ident_pkey
->pkey
->pkey
.dsa
) == NULL
) {
2218 msyslog(LOG_NOTICE
, "crypto_iff: defective key");
2221 if (peer
->iffval
== NULL
) {
2222 msyslog(LOG_NOTICE
, "crypto_iff: missing challenge");
2227 * Extract the k + b r and g^k values from the response.
2229 bctx
= BN_CTX_new(); bk
= BN_new(); bn
= BN_new();
2230 len
= ntohl(ep
->vallen
);
2231 ptr
= (u_char
*)ep
->pkt
;
2232 if ((sdsa
= d2i_DSA_SIG(NULL
, &ptr
, len
)) == NULL
) {
2233 BN_free(bn
); BN_free(bk
); BN_CTX_free(bctx
);
2234 msyslog(LOG_ERR
, "crypto_iff: %s",
2235 ERR_error_string(ERR_get_error(), NULL
));
2240 * Compute g^(k + b r) g^(q - b)r mod p.
2242 BN_mod_exp(bn
, dsa
->pub_key
, peer
->iffval
, dsa
->p
, bctx
);
2243 BN_mod_exp(bk
, dsa
->g
, sdsa
->r
, dsa
->p
, bctx
);
2244 BN_mod_mul(bn
, bn
, bk
, dsa
->p
, bctx
);
2247 * Verify the hash of the result matches hash(x).
2250 temp
= BN_cmp(bn
, sdsa
->s
);
2251 BN_free(bn
); BN_free(bk
); BN_CTX_free(bctx
);
2252 BN_free(peer
->iffval
);
2253 peer
->iffval
= NULL
;
2258 msyslog(LOG_NOTICE
, "crypto_iff: identity not verified");
2264 ***********************************************************************
2266 * The following routines implement the Guillou-Quisquater (GQ) *
2269 ***********************************************************************
2271 * The Guillou-Quisquater (GQ) identity scheme is intended for use when
2272 * the certificate can be used to convey public parameters. The scheme
2273 * uses a X509v3 certificate extension field do convey the public key of
2274 * a private key known only to servers. There are two kinds of files:
2275 * encrypted server files that contain private and public values and
2276 * nonencrypted client files that contain only public values. New
2277 * generations of server files must be securely transmitted to all
2278 * servers of the group; client files can be distributed by any means.
2279 * The scheme is self contained and independent of new generations of
2280 * host keys and sign keys. The scheme is self contained and independent
2281 * of new generations of host keys and sign keys.
2283 * The GQ parameters hide in a RSA cuckoo structure which uses the same
2284 * parameters. The values are used by an identity scheme based on RSA
2285 * cryptography and described in Stimson p. 300 (with errors). The 512-
2286 * bit public modulus is n = p q, where p and q are secret large primes.
2287 * The TA rolls private random group key b as RSA exponent. These values
2288 * are known to all group members.
2290 * When rolling new certificates, a server recomputes the private and
2291 * public keys. The private key u is a random roll, while the public key
2292 * is the inverse obscured by the group key v = (u^-1)^b. These values
2293 * replace the private and public keys normally generated by the RSA
2294 * scheme. Alice challenges Bob to confirm identity using the protocol
2299 * The scheme goes like this. Both Alice and Bob have the same modulus n
2300 * and some random b as the group key. These values are computed and
2301 * distributed in advance via secret means, although only the group key
2302 * b is truly secret. Each has a private random private key u and public
2303 * key (u^-1)^b, although not necessarily the same ones. Bob and Alice
2304 * can regenerate the key pair from time to time without affecting
2305 * operations. The public key is conveyed on the certificate in an
2306 * extension field; the private key is never revealed.
2308 * Alice rolls new random challenge r and sends to Bob in the GQ
2309 * request message. Bob rolls new random k, then computes y = k u^r mod
2310 * n and x = k^b mod n and sends (y, hash(x)) to Alice in the response
2311 * message. Besides making the response shorter, the hash makes it
2312 * effectivey impossible for an intruder to solve for b by observing
2313 * a number of these messages.
2315 * Alice receives the response and computes y^b v^r mod n. After a bit
2316 * of algebra, this simplifies to k^b. If the hash of this result
2317 * matches hash(x), Alice knows that Bob has the group key b. The signed
2318 * response binds this knowledge to Bob's private key and the public key
2319 * previously received in his certificate.
2321 * crypto_alice2 - construct Alice's challenge in GQ scheme
2325 * XEVNT_ID bad or missing group key
2326 * XEVNT_PUB bad or missing public key
2330 struct peer
*peer
, /* peer pointer */
2331 struct value
*vp
/* value pointer */
2334 RSA
*rsa
; /* GQ parameters */
2335 BN_CTX
*bctx
; /* BIGNUM context */
2336 EVP_MD_CTX ctx
; /* signature context */
2341 * The identity parameters must have correct format and content.
2343 if (peer
->ident_pkey
== NULL
)
2346 if ((rsa
= peer
->ident_pkey
->pkey
->pkey
.rsa
) == NULL
) {
2347 msyslog(LOG_NOTICE
, "crypto_alice2: defective key");
2352 * Roll new random r (0 < r < n).
2354 if (peer
->iffval
!= NULL
)
2355 BN_free(peer
->iffval
);
2356 peer
->iffval
= BN_new();
2357 len
= BN_num_bytes(rsa
->n
);
2358 BN_rand(peer
->iffval
, len
* 8, -1, 1); /* r mod n */
2359 bctx
= BN_CTX_new();
2360 BN_mod(peer
->iffval
, peer
->iffval
, rsa
->n
, bctx
);
2364 * Sign and send to Bob. The filestamp is from the local file.
2366 memset(vp
, 0, sizeof(struct value
));
2367 tstamp
= crypto_time();
2368 vp
->tstamp
= htonl(tstamp
);
2369 vp
->fstamp
= htonl(peer
->ident_pkey
->fstamp
);
2370 vp
->vallen
= htonl(len
);
2371 vp
->ptr
= emalloc(len
);
2372 BN_bn2bin(peer
->iffval
, vp
->ptr
);
2376 vp
->sig
= emalloc(sign_siglen
);
2377 EVP_SignInit(&ctx
, sign_digest
);
2378 EVP_SignUpdate(&ctx
, (u_char
*)&vp
->tstamp
, 12);
2379 EVP_SignUpdate(&ctx
, vp
->ptr
, len
);
2380 if (EVP_SignFinal(&ctx
, vp
->sig
, &len
, sign_pkey
))
2381 vp
->siglen
= htonl(sign_siglen
);
2387 * crypto_bob2 - construct Bob's response to Alice's challenge
2391 * XEVNT_ERR protocol error
2392 * XEVNT_ID bad or missing group key
2396 struct exten
*ep
, /* extension pointer */
2397 struct value
*vp
/* value pointer */
2400 RSA
*rsa
; /* GQ parameters */
2401 DSA_SIG
*sdsa
; /* DSA parameters */
2402 BN_CTX
*bctx
; /* BIGNUM context */
2403 EVP_MD_CTX ctx
; /* signature context */
2404 tstamp_t tstamp
; /* NTP timestamp */
2405 BIGNUM
*r
, *k
, *g
, *y
;
2410 * If the GQ parameters are not valid, something awful
2411 * happened or we are being tormented.
2413 if (gqkey_info
== NULL
) {
2414 msyslog(LOG_NOTICE
, "crypto_bob2: scheme unavailable");
2417 rsa
= gqkey_info
->pkey
->pkey
.rsa
;
2420 * Extract r from the challenge.
2422 len
= ntohl(ep
->vallen
);
2423 if ((r
= BN_bin2bn((u_char
*)ep
->pkt
, len
, NULL
)) == NULL
) {
2424 msyslog(LOG_ERR
, "crypto_bob2: %s",
2425 ERR_error_string(ERR_get_error(), NULL
));
2430 * Bob rolls random k (0 < k < n), computes y = k u^r mod n and
2431 * x = k^b mod n, then sends (y, hash(x)) to Alice.
2433 bctx
= BN_CTX_new(); k
= BN_new(); g
= BN_new(); y
= BN_new();
2434 sdsa
= DSA_SIG_new();
2435 BN_rand(k
, len
* 8, -1, 1); /* k */
2436 BN_mod(k
, k
, rsa
->n
, bctx
);
2437 BN_mod_exp(y
, rsa
->p
, r
, rsa
->n
, bctx
); /* u^r mod n */
2438 BN_mod_mul(y
, k
, y
, rsa
->n
, bctx
); /* k u^r mod n */
2439 sdsa
->r
= BN_dup(y
);
2440 BN_mod_exp(g
, k
, rsa
->e
, rsa
->n
, bctx
); /* k^b mod n */
2442 sdsa
->s
= BN_dup(g
);
2444 BN_free(r
); BN_free(k
); BN_free(g
); BN_free(y
);
2447 RSA_print_fp(stdout
, rsa
, 0);
2451 * Encode the values in ASN.1 and sign. The filestamp is from
2454 len
= i2d_DSA_SIG(sdsa
, NULL
);
2456 msyslog(LOG_ERR
, "crypto_bob2: %s",
2457 ERR_error_string(ERR_get_error(), NULL
));
2461 memset(vp
, 0, sizeof(struct value
));
2462 tstamp
= crypto_time();
2463 vp
->tstamp
= htonl(tstamp
);
2464 vp
->fstamp
= htonl(gqkey_info
->fstamp
);
2465 vp
->vallen
= htonl(len
);
2468 i2d_DSA_SIG(sdsa
, &ptr
);
2473 vp
->sig
= emalloc(sign_siglen
);
2474 EVP_SignInit(&ctx
, sign_digest
);
2475 EVP_SignUpdate(&ctx
, (u_char
*)&vp
->tstamp
, 12);
2476 EVP_SignUpdate(&ctx
, vp
->ptr
, len
);
2477 if (EVP_SignFinal(&ctx
, vp
->sig
, &len
, sign_pkey
))
2478 vp
->siglen
= htonl(sign_siglen
);
2484 * crypto_gq - verify Bob's response to Alice's challenge
2488 * XEVNT_ERR protocol error
2489 * XEVNT_FSP bad filestamp
2490 * XEVNT_ID bad or missing group keys
2491 * XEVNT_PUB bad or missing public key
2495 struct exten
*ep
, /* extension pointer */
2496 struct peer
*peer
/* peer structure pointer */
2499 RSA
*rsa
; /* GQ parameters */
2500 BN_CTX
*bctx
; /* BIGNUM context */
2501 DSA_SIG
*sdsa
; /* RSA signature context fake */
2508 * If the GQ parameters are not valid or no challenge was sent,
2509 * something awful happened or we are being tormented. Note that
2510 * the filestamp on the local key file can be greater than on
2511 * the remote parameter file if the keys have been refreshed.
2513 if (peer
->ident_pkey
== NULL
) {
2514 msyslog(LOG_NOTICE
, "crypto_gq: scheme unavailable");
2517 if (ntohl(ep
->fstamp
) < peer
->ident_pkey
->fstamp
) {
2518 msyslog(LOG_NOTICE
, "crypto_gq: invalid filestamp %u",
2522 if ((rsa
= peer
->ident_pkey
->pkey
->pkey
.rsa
) == NULL
) {
2523 msyslog(LOG_NOTICE
, "crypto_gq: defective key");
2526 if (peer
->iffval
== NULL
) {
2527 msyslog(LOG_NOTICE
, "crypto_gq: missing challenge");
2532 * Extract the y = k u^r and hash(x = k^b) values from the
2535 bctx
= BN_CTX_new(); y
= BN_new(); v
= BN_new();
2536 len
= ntohl(ep
->vallen
);
2537 ptr
= (u_char
*)ep
->pkt
;
2538 if ((sdsa
= d2i_DSA_SIG(NULL
, &ptr
, len
)) == NULL
) {
2539 BN_CTX_free(bctx
); BN_free(y
); BN_free(v
);
2540 msyslog(LOG_ERR
, "crypto_gq: %s",
2541 ERR_error_string(ERR_get_error(), NULL
));
2546 * Compute v^r y^b mod n.
2548 if (peer
->grpkey
== NULL
) {
2549 msyslog(LOG_NOTICE
, "crypto_gq: missing group key");
2552 BN_mod_exp(v
, peer
->grpkey
, peer
->iffval
, rsa
->n
, bctx
);
2554 BN_mod_exp(y
, sdsa
->r
, rsa
->e
, rsa
->n
, bctx
); /* y^b mod n */
2555 BN_mod_mul(y
, v
, y
, rsa
->n
, bctx
); /* v^r y^b mod n */
2558 * Verify the hash of the result matches hash(x).
2561 temp
= BN_cmp(y
, sdsa
->s
);
2562 BN_CTX_free(bctx
); BN_free(y
); BN_free(v
);
2563 BN_free(peer
->iffval
);
2564 peer
->iffval
= NULL
;
2569 msyslog(LOG_NOTICE
, "crypto_gq: identity not verified");
2575 ***********************************************************************
2577 * The following routines implement the Mu-Varadharajan (MV) identity *
2580 ***********************************************************************
2582 * The Mu-Varadharajan (MV) cryptosystem was originally intended when
2583 * servers broadcast messages to clients, but clients never send
2584 * messages to servers. There is one encryption key for the server and a
2585 * separate decryption key for each client. It operated something like a
2586 * pay-per-view satellite broadcasting system where the session key is
2587 * encrypted by the broadcaster and the decryption keys are held in a
2588 * tamperproof set-top box.
2590 * The MV parameters and private encryption key hide in a DSA cuckoo
2591 * structure which uses the same parameters, but generated in a
2592 * different way. The values are used in an encryption scheme similar to
2593 * El Gamal cryptography and a polynomial formed from the expansion of
2594 * product terms (x - x[j]), as described in Mu, Y., and V.
2595 * Varadharajan: Robust and Secure Broadcasting, Proc. Indocrypt 2001,
2596 * 223-231. The paper has significant errors and serious omissions.
2598 * Let q be the product of n distinct primes s1[j] (j = 1...n), where
2599 * each s1[j] has m significant bits. Let p be a prime p = 2 * q + 1, so
2600 * that q and each s1[j] divide p - 1 and p has M = n * m + 1
2601 * significant bits. Let g be a generator of Zp; that is, gcd(g, p - 1)
2602 * = 1 and g^q = 1 mod p. We do modular arithmetic over Zq and then
2603 * project into Zp* as exponents of g. Sometimes we have to compute an
2604 * inverse b^-1 of random b in Zq, but for that purpose we require
2605 * gcd(b, q) = 1. We expect M to be in the 500-bit range and n
2606 * relatively small, like 30. These are the parameters of the scheme and
2607 * they are expensive to compute.
2609 * We set up an instance of the scheme as follows. A set of random
2610 * values x[j] mod q (j = 1...n), are generated as the zeros of a
2611 * polynomial of order n. The product terms (x - x[j]) are expanded to
2612 * form coefficients a[i] mod q (i = 0...n) in powers of x. These are
2613 * used as exponents of the generator g mod p to generate the private
2614 * encryption key A. The pair (gbar, ghat) of public server keys and the
2615 * pairs (xbar[j], xhat[j]) (j = 1...n) of private client keys are used
2616 * to construct the decryption keys. The devil is in the details.
2618 * This routine generates a private server encryption file including the
2619 * private encryption key E and partial decryption keys gbar and ghat.
2620 * It then generates public client decryption files including the public
2621 * keys xbar[j] and xhat[j] for each client j. The partial decryption
2622 * files are used to compute the inverse of E. These values are suitably
2623 * blinded so secrets are not revealed.
2625 * The distinguishing characteristic of this scheme is the capability to
2626 * revoke keys. Included in the calculation of E, gbar and ghat is the
2627 * product s = prod(s1[j]) (j = 1...n) above. If the factor s1[j] is
2628 * subsequently removed from the product and E, gbar and ghat
2629 * recomputed, the jth client will no longer be able to compute E^-1 and
2630 * thus unable to decrypt the messageblock.
2634 * The scheme goes like this. Bob has the server values (p, E, q, gbar,
2635 * ghat) and Alice has the client values (p, xbar, xhat).
2637 * Alice rolls new random nonce r mod p and sends to Bob in the MV
2638 * request message. Bob rolls random nonce k mod q, encrypts y = r E^k
2639 * mod p and sends (y, gbar^k, ghat^k) to Alice.
2641 * Alice receives the response and computes the inverse (E^k)^-1 from
2642 * the partial decryption keys gbar^k, ghat^k, xbar and xhat. She then
2643 * decrypts y and verifies it matches the original r. The signed
2644 * response binds this knowledge to Bob's private key and the public key
2645 * previously received in his certificate.
2647 * crypto_alice3 - construct Alice's challenge in MV scheme
2651 * XEVNT_ID bad or missing group key
2652 * XEVNT_PUB bad or missing public key
2656 struct peer
*peer
, /* peer pointer */
2657 struct value
*vp
/* value pointer */
2660 DSA
*dsa
; /* MV parameters */
2661 BN_CTX
*bctx
; /* BIGNUM context */
2662 EVP_MD_CTX ctx
; /* signature context */
2667 * The identity parameters must have correct format and content.
2669 if (peer
->ident_pkey
== NULL
)
2672 if ((dsa
= peer
->ident_pkey
->pkey
->pkey
.dsa
) == NULL
) {
2673 msyslog(LOG_NOTICE
, "crypto_alice3: defective key");
2678 * Roll new random r (0 < r < q).
2680 if (peer
->iffval
!= NULL
)
2681 BN_free(peer
->iffval
);
2682 peer
->iffval
= BN_new();
2683 len
= BN_num_bytes(dsa
->p
);
2684 BN_rand(peer
->iffval
, len
* 8, -1, 1); /* r mod p */
2685 bctx
= BN_CTX_new();
2686 BN_mod(peer
->iffval
, peer
->iffval
, dsa
->p
, bctx
);
2690 * Sign and send to Bob. The filestamp is from the local file.
2692 memset(vp
, 0, sizeof(struct value
));
2693 tstamp
= crypto_time();
2694 vp
->tstamp
= htonl(tstamp
);
2695 vp
->fstamp
= htonl(peer
->ident_pkey
->fstamp
);
2696 vp
->vallen
= htonl(len
);
2697 vp
->ptr
= emalloc(len
);
2698 BN_bn2bin(peer
->iffval
, vp
->ptr
);
2702 vp
->sig
= emalloc(sign_siglen
);
2703 EVP_SignInit(&ctx
, sign_digest
);
2704 EVP_SignUpdate(&ctx
, (u_char
*)&vp
->tstamp
, 12);
2705 EVP_SignUpdate(&ctx
, vp
->ptr
, len
);
2706 if (EVP_SignFinal(&ctx
, vp
->sig
, &len
, sign_pkey
))
2707 vp
->siglen
= htonl(sign_siglen
);
2713 * crypto_bob3 - construct Bob's response to Alice's challenge
2717 * XEVNT_ERR protocol error
2721 struct exten
*ep
, /* extension pointer */
2722 struct value
*vp
/* value pointer */
2725 DSA
*dsa
; /* MV parameters */
2726 DSA
*sdsa
; /* DSA signature context fake */
2727 BN_CTX
*bctx
; /* BIGNUM context */
2728 EVP_MD_CTX ctx
; /* signature context */
2729 tstamp_t tstamp
; /* NTP timestamp */
2735 * If the MV parameters are not valid, something awful
2736 * happened or we are being tormented.
2738 if (mvkey_info
== NULL
) {
2739 msyslog(LOG_NOTICE
, "crypto_bob3: scheme unavailable");
2742 dsa
= mvkey_info
->pkey
->pkey
.dsa
;
2745 * Extract r from the challenge.
2747 len
= ntohl(ep
->vallen
);
2748 if ((r
= BN_bin2bn((u_char
*)ep
->pkt
, len
, NULL
)) == NULL
) {
2749 msyslog(LOG_ERR
, "crypto_bob3: %s",
2750 ERR_error_string(ERR_get_error(), NULL
));
2755 * Bob rolls random k (0 < k < q), making sure it is not a
2756 * factor of q. He then computes y = r A^k and sends (y, gbar^k,
2757 * and ghat^k) to Alice.
2759 bctx
= BN_CTX_new(); k
= BN_new(); u
= BN_new();
2761 sdsa
->p
= BN_new(); sdsa
->q
= BN_new(); sdsa
->g
= BN_new();
2763 BN_rand(k
, BN_num_bits(dsa
->q
), 0, 0);
2764 BN_mod(k
, k
, dsa
->q
, bctx
);
2765 BN_gcd(u
, k
, dsa
->q
, bctx
);
2769 BN_mod_exp(u
, dsa
->g
, k
, dsa
->p
, bctx
); /* A^k r */
2770 BN_mod_mul(sdsa
->p
, u
, r
, dsa
->p
, bctx
);
2771 BN_mod_exp(sdsa
->q
, dsa
->priv_key
, k
, dsa
->p
, bctx
); /* gbar */
2772 BN_mod_exp(sdsa
->g
, dsa
->pub_key
, k
, dsa
->p
, bctx
); /* ghat */
2773 BN_CTX_free(bctx
); BN_free(k
); BN_free(r
); BN_free(u
);
2776 DSA_print_fp(stdout
, sdsa
, 0);
2780 * Encode the values in ASN.1 and sign. The filestamp is from
2783 memset(vp
, 0, sizeof(struct value
));
2784 tstamp
= crypto_time();
2785 vp
->tstamp
= htonl(tstamp
);
2786 vp
->fstamp
= htonl(mvkey_info
->fstamp
);
2787 len
= i2d_DSAparams(sdsa
, NULL
);
2789 msyslog(LOG_ERR
, "crypto_bob3: %s",
2790 ERR_error_string(ERR_get_error(), NULL
));
2794 vp
->vallen
= htonl(len
);
2797 i2d_DSAparams(sdsa
, &ptr
);
2802 vp
->sig
= emalloc(sign_siglen
);
2803 EVP_SignInit(&ctx
, sign_digest
);
2804 EVP_SignUpdate(&ctx
, (u_char
*)&vp
->tstamp
, 12);
2805 EVP_SignUpdate(&ctx
, vp
->ptr
, len
);
2806 if (EVP_SignFinal(&ctx
, vp
->sig
, &len
, sign_pkey
))
2807 vp
->siglen
= htonl(sign_siglen
);
2813 * crypto_mv - verify Bob's response to Alice's challenge
2817 * XEVNT_ERR protocol error
2818 * XEVNT_FSP bad filestamp
2819 * XEVNT_ID bad or missing group key
2820 * XEVNT_PUB bad or missing public key
2824 struct exten
*ep
, /* extension pointer */
2825 struct peer
*peer
/* peer structure pointer */
2828 DSA
*dsa
; /* MV parameters */
2829 DSA
*sdsa
; /* DSA parameters */
2830 BN_CTX
*bctx
; /* BIGNUM context */
2837 * If the MV parameters are not valid or no challenge was sent,
2838 * something awful happened or we are being tormented.
2840 if (peer
->ident_pkey
== NULL
) {
2841 msyslog(LOG_NOTICE
, "crypto_mv: scheme unavailable");
2844 if (ntohl(ep
->fstamp
) != peer
->ident_pkey
->fstamp
) {
2845 msyslog(LOG_NOTICE
, "crypto_mv: invalid filestamp %u",
2849 if ((dsa
= peer
->ident_pkey
->pkey
->pkey
.dsa
) == NULL
) {
2850 msyslog(LOG_NOTICE
, "crypto_mv: defective key");
2853 if (peer
->iffval
== NULL
) {
2854 msyslog(LOG_NOTICE
, "crypto_mv: missing challenge");
2859 * Extract the y, gbar and ghat values from the response.
2861 bctx
= BN_CTX_new(); k
= BN_new(); u
= BN_new(); v
= BN_new();
2862 len
= ntohl(ep
->vallen
);
2863 ptr
= (u_char
*)ep
->pkt
;
2864 if ((sdsa
= d2i_DSAparams(NULL
, &ptr
, len
)) == NULL
) {
2865 msyslog(LOG_ERR
, "crypto_mv: %s",
2866 ERR_error_string(ERR_get_error(), NULL
));
2871 * Compute (gbar^xhat ghat^xbar) mod p.
2873 BN_mod_exp(u
, sdsa
->q
, dsa
->pub_key
, dsa
->p
, bctx
);
2874 BN_mod_exp(v
, sdsa
->g
, dsa
->priv_key
, dsa
->p
, bctx
);
2875 BN_mod_mul(u
, u
, v
, dsa
->p
, bctx
);
2876 BN_mod_mul(u
, u
, sdsa
->p
, dsa
->p
, bctx
);
2879 * The result should match r.
2881 temp
= BN_cmp(u
, peer
->iffval
);
2882 BN_CTX_free(bctx
); BN_free(k
); BN_free(u
); BN_free(v
);
2883 BN_free(peer
->iffval
);
2884 peer
->iffval
= NULL
;
2889 msyslog(LOG_NOTICE
, "crypto_mv: identity not verified");
2895 ***********************************************************************
2897 * The following routines are used to manipulate certificates *
2899 ***********************************************************************
2902 * cert_sign - sign x509 certificate equest and update value structure.
2904 * The certificate request includes a copy of the host certificate,
2905 * which includes the version number, subject name and public key of the
2906 * host. The resulting certificate includes these values plus the
2907 * serial number, issuer name and valid interval of the server. The
2908 * valid interval extends from the current time to the same time one
2909 * year hence. This may extend the life of the signed certificate beyond
2910 * that of the signer certificate.
2912 * It is convenient to use the NTP seconds of the current time as the
2913 * serial number. In the value structure the timestamp is the current
2914 * time and the filestamp is taken from the extension field. Note this
2915 * routine is called only when the client clock is synchronized to a
2916 * proventic source, so timestamp comparisons are valid.
2918 * The host certificate is valid from the time it was generated for a
2919 * period of one year. A signed certificate is valid from the time of
2920 * signature for a period of one year, but only the host certificate (or
2921 * sign certificate if used) is actually used to encrypt and decrypt
2922 * signatures. The signature trail is built from the client via the
2923 * intermediate servers to the trusted server. Each signature on the
2924 * trail must be valid at the time of signature, but it could happen
2925 * that a signer certificate expire before the signed certificate, which
2926 * remains valid until its expiration.
2930 * XEVNT_CRT bad or missing certificate
2931 * XEVNT_PER host certificate expired
2932 * XEVNT_PUB bad or missing public key
2933 * XEVNT_VFY certificate not verified
2937 struct exten
*ep
, /* extension field pointer */
2938 struct value
*vp
/* value pointer */
2941 X509
*req
; /* X509 certificate request */
2942 X509
*cert
; /* X509 certificate */
2943 X509_EXTENSION
*ext
; /* certificate extension */
2944 ASN1_INTEGER
*serial
; /* serial number */
2945 X509_NAME
*subj
; /* distinguished (common) name */
2946 EVP_PKEY
*pkey
; /* public key */
2947 EVP_MD_CTX ctx
; /* message digest context */
2948 tstamp_t tstamp
; /* NTP timestamp */
2954 * Decode ASN.1 objects and construct certificate structure.
2955 * Make sure the system clock is synchronized to a proventic
2958 tstamp
= crypto_time();
2962 ptr
= (u_char
*)ep
->pkt
;
2963 if ((req
= d2i_X509(NULL
, &ptr
, ntohl(ep
->vallen
))) == NULL
) {
2964 msyslog(LOG_ERR
, "cert_sign: %s",
2965 ERR_error_string(ERR_get_error(), NULL
));
2969 * Extract public key and check for errors.
2971 if ((pkey
= X509_get_pubkey(req
)) == NULL
) {
2972 msyslog(LOG_ERR
, "cert_sign: %s",
2973 ERR_error_string(ERR_get_error(), NULL
));
2979 * Generate X509 certificate signed by this server. If this is a
2980 * trusted host, the issuer name is the group name; otherwise,
2981 * it is the host name. Also copy any extensions that might be
2985 X509_set_version(cert
, X509_get_version(req
));
2986 serial
= ASN1_INTEGER_new();
2987 ASN1_INTEGER_set(serial
, tstamp
);
2988 X509_set_serialNumber(cert
, serial
);
2989 X509_gmtime_adj(X509_get_notBefore(cert
), 0L);
2990 X509_gmtime_adj(X509_get_notAfter(cert
), YEAR
);
2991 subj
= X509_get_issuer_name(cert
);
2992 X509_NAME_add_entry_by_txt(subj
, "commonName", MBSTRING_ASC
,
2993 hostval
.ptr
, strlen(hostval
.ptr
), -1, 0);
2994 subj
= X509_get_subject_name(req
);
2995 X509_set_subject_name(cert
, subj
);
2996 X509_set_pubkey(cert
, pkey
);
2997 ext
= X509_get_ext(req
, 0);
2998 temp
= X509_get_ext_count(req
);
2999 for (i
= 0; i
< temp
; i
++) {
3000 ext
= X509_get_ext(req
, i
);
3001 X509_add_ext(cert
, ext
, -1);
3006 * Sign and verify the client certificate, but only if the host
3007 * certificate has not expired.
3009 if (tstamp
< cert_host
->first
|| tstamp
> cert_host
->last
) {
3013 X509_sign(cert
, sign_pkey
, sign_digest
);
3014 if (X509_verify(cert
, sign_pkey
) <= 0) {
3015 msyslog(LOG_ERR
, "cert_sign: %s",
3016 ERR_error_string(ERR_get_error(), NULL
));
3020 len
= i2d_X509(cert
, NULL
);
3023 * Build and sign the value structure. We have to sign it here,
3024 * since the response has to be returned right away. This is a
3027 memset(vp
, 0, sizeof(struct value
));
3028 vp
->tstamp
= htonl(tstamp
);
3029 vp
->fstamp
= ep
->fstamp
;
3030 vp
->vallen
= htonl(len
);
3031 vp
->ptr
= emalloc(len
);
3033 i2d_X509(cert
, (unsigned char **)&ptr
);
3036 vp
->sig
= emalloc(sign_siglen
);
3037 EVP_SignInit(&ctx
, sign_digest
);
3038 EVP_SignUpdate(&ctx
, (u_char
*)vp
, 12);
3039 EVP_SignUpdate(&ctx
, vp
->ptr
, len
);
3040 if (EVP_SignFinal(&ctx
, vp
->sig
, &len
, sign_pkey
))
3041 vp
->siglen
= htonl(sign_siglen
);
3045 X509_print_fp(stdout
, cert
);
3053 * cert_install - install certificate in certificate cache
3055 * This routine encodes an extension field into a certificate info/value
3056 * structure. It searches the certificate list for duplicates and
3057 * expunges whichever is older. Finally, it inserts this certificate
3058 * first on the list.
3060 * Returns certificate info pointer if valid, NULL if not.
3064 struct exten
*ep
, /* cert info/value */
3065 struct peer
*peer
/* peer structure */
3068 struct cert_info
*cp
, *xp
, **zp
;
3071 * Parse and validate the signed certificate. If valid,
3072 * construct the info/value structure; otherwise, scamper home
3075 if ((cp
= cert_parse((u_char
*)ep
->pkt
, (long)ntohl(ep
->vallen
),
3076 (tstamp_t
)ntohl(ep
->fstamp
))) == NULL
)
3080 * Scan certificate list looking for another certificate with
3081 * the same subject and issuer. If another is found with the
3082 * same or older filestamp, unlink it and return the goodies to
3083 * the heap. If another is found with a later filestamp, discard
3084 * the new one and leave the building with the old one.
3086 * Make a note to study this issue again. An earlier certificate
3087 * with a long lifetime might be overtaken by a later
3088 * certificate with a short lifetime, thus invalidating the
3089 * earlier signature. However, we gotta find a way to leak old
3090 * stuff from the cache, so we do it anyway.
3093 for (xp
= cinfo
; xp
!= NULL
; xp
= xp
->link
) {
3094 if (strcmp(cp
->subject
, xp
->subject
) == 0 &&
3095 strcmp(cp
->issuer
, xp
->issuer
) == 0) {
3096 if (ntohl(cp
->cert
.fstamp
) <=
3097 ntohl(xp
->cert
.fstamp
)) {
3113 cp
->flags
|= CERT_VALID
;
3120 * cert_hike - verify the signature using the issuer public key
3124 * XEVNT_CRT bad or missing certificate
3125 * XEVNT_PER host certificate expired
3126 * XEVNT_VFY certificate not verified
3130 struct peer
*peer
, /* peer structure pointer */
3131 struct cert_info
*yp
/* issuer certificate */
3134 struct cert_info
*xp
; /* subject certificate */
3135 X509
*cert
; /* X509 certificate */
3139 * Save the issuer on the new certificate, but remember the old
3142 if (peer
->issuer
!= NULL
)
3144 peer
->issuer
= emalloc(strlen(yp
->issuer
) + 1);
3145 strcpy(peer
->issuer
, yp
->issuer
);
3150 * If subject Y matches issuer Y, then the certificate trail is
3151 * complete. If Y is not trusted, the server certificate has yet
3152 * been signed, so keep trying. Otherwise, save the group key
3153 * and light the valid bit. If the host certificate is trusted,
3154 * do not execute a sign exchange. If no identity scheme is in
3155 * use, light the identity and proventic bits.
3157 if (strcmp(yp
->subject
, yp
->issuer
) == 0) {
3158 if (!(yp
->flags
& CERT_TRUST
))
3161 peer
->grpkey
= yp
->grpkey
;
3162 peer
->crypto
|= CRYPTO_FLAG_CERT
;
3163 if (!(peer
->crypto
& CRYPTO_FLAG_MASK
))
3164 peer
->crypto
|= CRYPTO_FLAG_VRFY
|
3168 * If the server has an an identity scheme, fetch the
3169 * identity credentials. If not, the identity is
3170 * verified only by the trusted certificate. The next
3171 * signature will set the server proventic.
3173 if (!(peer
->crypto
& CRYPTO_FLAG_MASK
) ||
3174 sys_groupname
== NULL
)
3175 peer
->crypto
|= CRYPTO_FLAG_VRFY
;
3179 * If X exists, verify signature X using public key Y.
3184 ptr
= (u_char
*)xp
->cert
.ptr
;
3185 cert
= d2i_X509(NULL
, &ptr
, ntohl(xp
->cert
.vallen
));
3187 xp
->flags
|= CERT_ERROR
;
3190 if (X509_verify(cert
, yp
->pkey
) <= 0) {
3192 xp
->flags
|= CERT_ERROR
;
3198 * Signature X is valid only if it begins during the
3201 if (xp
->first
< yp
->first
|| xp
->first
> yp
->last
) {
3202 xp
->flags
|= CERT_ERROR
;
3205 xp
->flags
|= CERT_SIGN
;
3211 * cert_parse - parse x509 certificate and create info/value structures.
3213 * The server certificate includes the version number, issuer name,
3214 * subject name, public key and valid date interval. If the issuer name
3215 * is the same as the subject name, the certificate is self signed and
3216 * valid only if the server is configured as trustable. If the names are
3217 * different, another issuer has signed the server certificate and
3218 * vouched for it. In this case the server certificate is valid if
3219 * verified by the issuer public key.
3221 * Returns certificate info/value pointer if valid, NULL if not.
3223 struct cert_info
* /* certificate information structure */
3225 u_char
*asn1cert
, /* X509 certificate */
3226 long len
, /* certificate length */
3227 tstamp_t fstamp
/* filestamp */
3230 X509
*cert
; /* X509 certificate */
3231 X509_EXTENSION
*ext
; /* X509v3 extension */
3232 struct cert_info
*ret
; /* certificate info/value */
3234 char pathbuf
[MAXFILENAME
];
3239 * Decode ASN.1 objects and construct certificate structure.
3242 if ((cert
= d2i_X509(NULL
, &ptr
, len
)) == NULL
) {
3243 msyslog(LOG_ERR
, "cert_parse: %s",
3244 ERR_error_string(ERR_get_error(), NULL
));
3249 X509_print_fp(stdout
, cert
);
3253 * Extract version, subject name and public key.
3255 ret
= emalloc(sizeof(struct cert_info
));
3256 memset(ret
, 0, sizeof(struct cert_info
));
3257 if ((ret
->pkey
= X509_get_pubkey(cert
)) == NULL
) {
3258 msyslog(LOG_ERR
, "cert_parse: %s",
3259 ERR_error_string(ERR_get_error(), NULL
));
3264 ret
->version
= X509_get_version(cert
);
3265 X509_NAME_oneline(X509_get_subject_name(cert
), pathbuf
,
3267 ptr
= strstr(pathbuf
, "CN=");
3269 msyslog(LOG_NOTICE
, "cert_parse: invalid subject %s",
3275 ret
->subject
= estrdup(ptr
+ 3);
3278 * Extract remaining objects. Note that the NTP serial number is
3279 * the NTP seconds at the time of signing, but this might not be
3280 * the case for other authority. We don't bother to check the
3281 * objects at this time, since the real crunch can happen only
3282 * when the time is valid but not yet certificated.
3284 ret
->nid
= OBJ_obj2nid(cert
->cert_info
->signature
->algorithm
);
3285 ret
->digest
= (const EVP_MD
*)EVP_get_digestbynid(ret
->nid
);
3287 (u_long
)ASN1_INTEGER_get(X509_get_serialNumber(cert
));
3288 X509_NAME_oneline(X509_get_issuer_name(cert
), pathbuf
,
3290 if ((ptr
= strstr(pathbuf
, "CN=")) == NULL
) {
3291 msyslog(LOG_NOTICE
, "cert_parse: invalid issuer %s",
3297 ret
->issuer
= estrdup(ptr
+ 3);
3298 ret
->first
= asn2ntp(X509_get_notBefore(cert
));
3299 ret
->last
= asn2ntp(X509_get_notAfter(cert
));
3302 * Extract extension fields. These are ad hoc ripoffs of
3303 * currently assigned functions and will certainly be changed
3304 * before prime time.
3306 cnt
= X509_get_ext_count(cert
);
3307 for (i
= 0; i
< cnt
; i
++) {
3308 ext
= X509_get_ext(cert
, i
);
3309 temp
= OBJ_obj2nid(ext
->object
);
3313 * If a key_usage field is present, we decode whether
3314 * this is a trusted or private certificate. This is
3315 * dorky; all we want is to compare NIDs, but OpenSSL
3316 * insists on BIO text strings.
3318 case NID_ext_key_usage
:
3319 bp
= BIO_new(BIO_s_mem());
3320 X509V3_EXT_print(bp
, ext
, 0, 0);
3321 BIO_gets(bp
, pathbuf
, MAXFILENAME
);
3323 if (strcmp(pathbuf
, "Trust Root") == 0)
3324 ret
->flags
|= CERT_TRUST
;
3325 else if (strcmp(pathbuf
, "Private") == 0)
3326 ret
->flags
|= CERT_PRIV
;
3329 printf("cert_parse: %s: %s\n",
3330 OBJ_nid2ln(temp
), pathbuf
);
3335 * If a NID_subject_key_identifier field is present, it
3336 * contains the GQ public key.
3338 case NID_subject_key_identifier
:
3339 ret
->grpkey
= BN_bin2bn(&ext
->value
->data
[2],
3340 ext
->value
->length
- 2, NULL
);
3345 printf("cert_parse: %s\n",
3350 if (strcmp(ret
->subject
, ret
->issuer
) == 0) {
3353 * If certificate is self signed, verify signature.
3355 if (X509_verify(cert
, ret
->pkey
) <= 0) {
3357 "cert_parse: signature not verified %s",
3366 * Check for a certificate loop.
3368 if (strcmp(hostval
.ptr
, ret
->issuer
) == 0) {
3370 "cert_parse: certificate trail loop %s",
3379 * Verify certificate valid times. Note that certificates cannot
3382 if (ret
->first
> ret
->last
|| ret
->first
< fstamp
) {
3384 "cert_parse: invalid times %s first %u last %u fstamp %u",
3385 ret
->subject
, ret
->first
, ret
->last
, fstamp
);
3392 * Build the value structure to sign and send later.
3394 ret
->cert
.fstamp
= htonl(fstamp
);
3395 ret
->cert
.vallen
= htonl(len
);
3396 ret
->cert
.ptr
= emalloc(len
);
3397 memcpy(ret
->cert
.ptr
, asn1cert
, len
);
3404 * cert_free - free certificate information structure
3408 struct cert_info
*cinf
/* certificate info/value structure */
3411 if (cinf
->pkey
!= NULL
)
3412 EVP_PKEY_free(cinf
->pkey
);
3413 if (cinf
->subject
!= NULL
)
3414 free(cinf
->subject
);
3415 if (cinf
->issuer
!= NULL
)
3417 if (cinf
->grpkey
!= NULL
)
3418 BN_free(cinf
->grpkey
);
3419 value_free(&cinf
->cert
);
3425 * crypto_key - load cryptographic parameters and keys
3427 * This routine searches the key cache for matching name in the form
3428 * ntpkey_<key>_<name>, where <key> is one of host, sign, iff, gq, mv,
3429 * and <name> is the host/group name. If not found, it tries to load a
3430 * PEM-encoded file of the same name and extracts the filestamp from
3431 * the first line of the file name. It returns the key pointer if valid,
3434 static struct pkey_info
*
3436 char *cp
, /* file name */
3437 char *passwd1
, /* password */
3438 sockaddr_u
*addr
/* IP address */
3441 FILE *str
; /* file handle */
3442 struct pkey_info
*pkp
; /* generic key */
3443 EVP_PKEY
*pkey
= NULL
; /* public/private key */
3445 char filename
[MAXFILENAME
]; /* name of key file */
3446 char linkname
[MAXFILENAME
]; /* filestamp buffer) */
3447 char statstr
[NTP_MAXSTRLEN
]; /* statistics for filegen */
3451 * Search the key cache for matching key and name.
3453 for (pkp
= pkinfo
; pkp
!= NULL
; pkp
= pkp
->link
) {
3454 if (strcmp(cp
, pkp
->name
) == 0)
3459 * Open the key file. If the first character of the file name is
3460 * not '/', prepend the keys directory string. If something goes
3461 * wrong, abandon ship.
3464 strcpy(filename
, cp
);
3466 snprintf(filename
, MAXFILENAME
, "%s/%s", keysdir
, cp
);
3467 str
= fopen(filename
, "r");
3472 * Read the filestamp, which is contained in the first line.
3474 if ((ptr
= fgets(linkname
, MAXFILENAME
, str
)) == NULL
) {
3475 msyslog(LOG_ERR
, "crypto_key: empty file %s",
3480 if ((ptr
= strrchr(ptr
, '.')) == NULL
) {
3481 msyslog(LOG_ERR
, "crypto_key: no filestamp %s",
3486 if (sscanf(++ptr
, "%u", &fstamp
) != 1) {
3487 msyslog(LOG_ERR
, "crypto_key: invalid filestamp %s",
3494 * Read and decrypt PEM-encoded private key. If it fails to
3495 * decrypt, game over.
3497 pkey
= PEM_read_PrivateKey(str
, NULL
, NULL
, passwd1
);
3500 msyslog(LOG_ERR
, "crypto_key: %s",
3501 ERR_error_string(ERR_get_error(), NULL
));
3506 * Make a new entry in the key cache.
3508 pkp
= emalloc(sizeof(struct pkey_info
));
3512 pkp
->name
= emalloc(strlen(cp
) + 1);
3513 pkp
->fstamp
= fstamp
;
3514 strcpy(pkp
->name
, cp
);
3517 * Leave tracks in the cryptostats.
3519 if ((ptr
= strrchr(linkname
, '\n')) != NULL
)
3521 snprintf(statstr
, NTP_MAXSTRLEN
, "%s mod %d", &linkname
[2],
3522 EVP_PKEY_size(pkey
) * 8);
3523 record_crypto_stats(addr
, statstr
);
3526 printf("crypto_key: %s\n", statstr
);
3528 if (pkey
->type
== EVP_PKEY_DSA
)
3529 DSA_print_fp(stdout
, pkey
->pkey
.dsa
, 0);
3530 else if (pkey
->type
== EVP_PKEY_RSA
)
3531 RSA_print_fp(stdout
, pkey
->pkey
.rsa
, 0);
3539 ***********************************************************************
3541 * The following routines are used only at initialization time *
3543 ***********************************************************************
3546 * crypto_cert - load certificate from file
3548 * This routine loads an X.509 RSA or DSA certificate from a file and
3549 * constructs a info/cert value structure for this machine. The
3550 * structure includes a filestamp extracted from the file name. Later
3551 * the certificate can be sent to another machine on request.
3553 * Returns certificate info/value pointer if valid, NULL if not.
3555 static struct cert_info
* /* certificate information */
3557 char *cp
/* file name */
3560 struct cert_info
*ret
; /* certificate information */
3561 FILE *str
; /* file handle */
3562 char filename
[MAXFILENAME
]; /* name of certificate file */
3563 char linkname
[MAXFILENAME
]; /* filestamp buffer */
3564 char statstr
[NTP_MAXSTRLEN
]; /* statistics for filegen */
3565 tstamp_t fstamp
; /* filestamp */
3568 char *name
, *header
;
3572 * Open the certificate file. If the first character of the file
3573 * name is not '/', prepend the keys directory string. If
3574 * something goes wrong, abandon ship.
3577 strcpy(filename
, cp
);
3579 snprintf(filename
, MAXFILENAME
, "%s/%s", keysdir
, cp
);
3580 str
= fopen(filename
, "r");
3585 * Read the filestamp, which is contained in the first line.
3587 if ((ptr
= fgets(linkname
, MAXFILENAME
, str
)) == NULL
) {
3588 msyslog(LOG_ERR
, "crypto_cert: empty file %s",
3593 if ((ptr
= strrchr(ptr
, '.')) == NULL
) {
3594 msyslog(LOG_ERR
, "crypto_cert: no filestamp %s\n",
3599 if (sscanf(++ptr
, "%u", &fstamp
) != 1) {
3600 msyslog(LOG_ERR
, "crypto_cert: invalid filestamp %s\n",
3607 * Read PEM-encoded certificate and install.
3609 if (!PEM_read(str
, &name
, &header
, &data
, &len
)) {
3610 msyslog(LOG_ERR
, "crypto_cert: %s\n",
3611 ERR_error_string(ERR_get_error(), NULL
));
3617 if (strcmp(name
, "CERTIFICATE") != 0) {
3618 msyslog(LOG_NOTICE
, "crypto_cert: wrong PEM type %s",
3627 * Parse certificate and generate info/value structure. The
3628 * pointer and copy nonsense is due something broken in Solaris.
3630 ret
= cert_parse(data
, len
, fstamp
);
3635 if ((ptr
= strrchr(linkname
, '\n')) != NULL
)
3637 snprintf(statstr
, NTP_MAXSTRLEN
, "%s 0x%x len %lu",
3638 &linkname
[2], ret
->flags
, len
);
3639 record_crypto_stats(NULL
, statstr
);
3642 printf("crypto_cert: %s\n", statstr
);
3649 * crypto_setup - load keys, certificate and identity parameters
3651 * This routine loads the public/private host key and certificate. If
3652 * available, it loads the public/private sign key, which defaults to
3653 * the host key. The host key must be RSA, but the sign key can be
3654 * either RSA or DSA. If a trusted certificate, it loads the identity
3655 * parameters. In either case, the public key on the certificate must
3656 * agree with the sign key.
3658 * Required but missing files and inconsistent data and errors are
3659 * fatal. Allowing configuration to continue would be hazardous and
3660 * require really messy error checks.
3665 struct pkey_info
*pinfo
; /* private/public key */
3666 char filename
[MAXFILENAME
]; /* file name buffer */
3668 char statstr
[NTP_MAXSTRLEN
]; /* statistics for filegen */
3669 l_fp seed
; /* crypto PRNG seed as NTP timestamp */
3675 * Check for correct OpenSSL version and avoid initialization in
3676 * the case of multiple crypto commands.
3678 if (crypto_flags
& CRYPTO_FLAG_ENAB
) {
3680 "crypto_setup: spurious crypto command");
3683 ssl_check_version();
3686 * Load required random seed file and seed the random number
3687 * generator. Be default, it is found as .rnd in the user home
3688 * directory. The root home directory may be / or /root,
3689 * depending on the system. Wiggle the contents a bit and write
3690 * it back so the sequence does not repeat when we next restart.
3692 if (!RAND_status()) {
3693 if (rand_file
== NULL
) {
3694 RAND_file_name(filename
, sizeof(filename
));
3695 randfile
= filename
;
3696 } else if (*rand_file
!= '/') {
3697 snprintf(filename
, sizeof(filename
), "%s/%s",
3698 keysdir
, rand_file
);
3699 randfile
= filename
;
3701 randfile
= rand_file
;
3703 if ((bytes
= RAND_load_file(randfile
, -1)) == 0) {
3705 "crypto_setup: random seed file %s missing",
3710 RAND_seed(&seed
, sizeof(l_fp
));
3711 RAND_write_file(randfile
);
3715 "crypto_setup: OpenSSL version %lx random seed file %s bytes read %d\n",
3716 SSLeay(), randfile
, bytes
);
3721 * Initialize structures.
3723 if (sys_hostname
== NULL
) {
3724 gethostname(filename
, MAXFILENAME
);
3725 sys_hostname
= emalloc(strlen(filename
) + 1);
3726 strcpy(sys_hostname
, filename
);
3729 passwd
= sys_hostname
;
3730 memset(&hostval
, 0, sizeof(hostval
));
3731 memset(&pubkey
, 0, sizeof(pubkey
));
3732 memset(&tai_leap
, 0, sizeof(tai_leap
));
3735 * Load required host key from file "ntpkey_host_<hostname>". If
3736 * no host key file is not found or has invalid password, life
3737 * as we know it ends. The host key also becomes the default
3740 snprintf(filename
, MAXFILENAME
, "ntpkey_host_%s", sys_hostname
);
3741 pinfo
= crypto_key(filename
, passwd
, NULL
);
3742 if (pinfo
== NULL
) {
3744 "crypto_setup: host key file %s not found or corrupt",
3748 if (pinfo
->pkey
->type
!= EVP_PKEY_RSA
) {
3750 "crypto_setup: host key is not RSA key type");
3753 host_pkey
= pinfo
->pkey
;
3754 sign_pkey
= host_pkey
;
3755 hostval
.fstamp
= htonl(pinfo
->fstamp
);
3758 * Construct public key extension field for agreement scheme.
3760 len
= i2d_PublicKey(host_pkey
, NULL
);
3763 i2d_PublicKey(host_pkey
, &ptr
);
3764 pubkey
.fstamp
= hostval
.fstamp
;
3765 pubkey
.vallen
= htonl(len
);
3768 * Load optional sign key from file "ntpkey_sign_<hostname>". If
3769 * available, it becomes the sign key.
3771 snprintf(filename
, MAXFILENAME
, "ntpkey_sign_%s", sys_hostname
);
3772 pinfo
= crypto_key(filename
, passwd
, NULL
); if (pinfo
!= NULL
)
3773 sign_pkey
= pinfo
->pkey
;
3776 * Load required certificate from file "ntpkey_cert_<hostname>".
3778 snprintf(filename
, MAXFILENAME
, "ntpkey_cert_%s", sys_hostname
);
3779 cinfo
= crypto_cert(filename
);
3780 if (cinfo
== NULL
) {
3782 "crypto_setup: certificate file %s not found or corrupt",
3787 sign_digest
= cinfo
->digest
;
3788 sign_siglen
= EVP_PKEY_size(sign_pkey
);
3789 if (cinfo
->flags
& CERT_PRIV
)
3790 crypto_flags
|= CRYPTO_FLAG_PRIV
;
3793 * The certificate must be self-signed.
3795 if (strcmp(cinfo
->subject
, cinfo
->issuer
) != 0) {
3797 "crypto_setup: certificate %s is not self-signed",
3801 hostval
.vallen
= htonl(strlen(cinfo
->subject
));
3802 hostval
.ptr
= cinfo
->subject
;
3805 * If trusted certificate, the subject name must match the group
3808 if (cinfo
->flags
& CERT_TRUST
) {
3809 if (sys_groupname
== NULL
) {
3810 sys_groupname
= hostval
.ptr
;
3811 } else if (strcmp(hostval
.ptr
, sys_groupname
) != 0) {
3813 "crypto_setup: trusted certificate name %s does not match group name %s",
3814 hostval
.ptr
, sys_groupname
);
3818 if (sys_groupname
!= NULL
) {
3821 * Load optional IFF parameters from file
3822 * "ntpkey_iffkey_<groupname>".
3824 snprintf(filename
, MAXFILENAME
, "ntpkey_iffkey_%s",
3826 iffkey_info
= crypto_key(filename
, passwd
, NULL
);
3827 if (iffkey_info
!= NULL
)
3828 crypto_flags
|= CRYPTO_FLAG_IFF
;
3831 * Load optional GQ parameters from file
3832 * "ntpkey_gqkey_<groupname>".
3834 snprintf(filename
, MAXFILENAME
, "ntpkey_gqkey_%s",
3836 gqkey_info
= crypto_key(filename
, passwd
, NULL
);
3837 if (gqkey_info
!= NULL
)
3838 crypto_flags
|= CRYPTO_FLAG_GQ
;
3841 * Load optional MV parameters from file
3842 * "ntpkey_mvkey_<groupname>".
3844 snprintf(filename
, MAXFILENAME
, "ntpkey_mvkey_%s",
3846 mvkey_info
= crypto_key(filename
, passwd
, NULL
);
3847 if (mvkey_info
!= NULL
)
3848 crypto_flags
|= CRYPTO_FLAG_MV
;
3852 * We met the enemy and he is us. Now strike up the dance.
3854 crypto_flags
|= CRYPTO_FLAG_ENAB
| (cinfo
->nid
<< 16);
3855 snprintf(statstr
, NTP_MAXSTRLEN
,
3856 "setup 0x%x host %s %s", crypto_flags
, sys_hostname
,
3857 OBJ_nid2ln(cinfo
->nid
));
3858 record_crypto_stats(NULL
, statstr
);
3861 printf("crypto_setup: %s\n", statstr
);
3867 * crypto_config - configure data from the crypto command.
3871 int item
, /* configuration item */
3872 char *cp
/* item name */
3879 printf("crypto_config: item %d %s\n", item
, cp
);
3884 * Set host name (host).
3886 case CRYPTO_CONF_PRIV
:
3887 sys_hostname
= emalloc(strlen(cp
) + 1);
3888 strcpy(sys_hostname
, cp
);
3892 * Set group name (ident).
3894 case CRYPTO_CONF_IDENT
:
3895 sys_groupname
= emalloc(strlen(cp
) + 1);
3896 strcpy(sys_groupname
, cp
);
3900 * Set private key password (pw).
3902 case CRYPTO_CONF_PW
:
3903 passwd
= emalloc(strlen(cp
) + 1);
3908 * Set random seed file name (randfile).
3910 case CRYPTO_CONF_RAND
:
3911 rand_file
= emalloc(strlen(cp
) + 1);
3912 strcpy(rand_file
, cp
);
3916 * Set message digest NID.
3918 case CRYPTO_CONF_NID
:
3919 nid
= OBJ_sn2nid(cp
);
3922 "crypto_config: invalid digest name %s", cp
);
3929 int ntp_crypto_bs_pubkey
;
3930 # endif /* OPENSSL */