]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - contrib/ntp/ntpd/ntp_crypto.c
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / contrib / ntp / ntpd / ntp_crypto.c
1 /*
2  * ntp_crypto.c - NTP version 4 public key routines
3  */
4 #ifdef HAVE_CONFIG_H
5 #include <config.h>
6 #endif
7
8 #ifdef OPENSSL
9 #include <stdio.h>
10 #include <sys/types.h>
11 #include <sys/param.h>
12 #include <unistd.h>
13 #include <fcntl.h>
14
15 #include "ntpd.h"
16 #include "ntp_stdlib.h"
17 #include "ntp_unixtime.h"
18 #include "ntp_string.h"
19 #include <ntp_random.h>
20
21 #include "openssl/asn1_mac.h"
22 #include "openssl/bn.h"
23 #include "openssl/err.h"
24 #include "openssl/evp.h"
25 #include "openssl/pem.h"
26 #include "openssl/rand.h"
27 #include "openssl/x509v3.h"
28
29 #ifdef KERNEL_PLL
30 #include "ntp_syscall.h"
31 #endif /* KERNEL_PLL */
32
33 /*
34  * Extension field message format
35  *
36  * These are always signed and saved before sending in network byte
37  * order. They must be converted to and from host byte order for
38  * processing.
39  *
40  * +-------+-------+
41  * |   op  |  len  | <- extension pointer
42  * +-------+-------+
43  * |    assocID    |
44  * +---------------+
45  * |   timestamp   | <- value pointer
46  * +---------------+
47  * |   filestamp   |
48  * +---------------+
49  * |   value len   |
50  * +---------------+
51  * |               |
52  * =     value     =
53  * |               |
54  * +---------------+
55  * | signature len |
56  * +---------------+
57  * |               |
58  * =   signature   =
59  * |               |
60  * +---------------+
61  *
62  * The CRYPTO_RESP bit is set to 0 for requests, 1 for responses.
63  * Requests carry the association ID of the receiver; responses carry
64  * the association ID of the sender. Some messages include only the
65  * operation/length and association ID words and so have length 8
66  * octets. Ohers include the value structure and associated value and
67  * signature fields. These messages include the timestamp, filestamp,
68  * value and signature words and so have length at least 24 octets. The
69  * signature and/or value fields can be empty, in which case the
70  * respective length words are zero. An empty value with nonempty
71  * signature is syntactically valid, but semantically questionable.
72  *
73  * The filestamp represents the time when a cryptographic data file such
74  * as a public/private key pair is created. It follows every reference
75  * depending on that file and serves as a means to obsolete earlier data
76  * of the same type. The timestamp represents the time when the
77  * cryptographic data of the message were last signed. Creation of a
78  * cryptographic data file or signing a message can occur only when the
79  * creator or signor is synchronized to an authoritative source and
80  * proventicated to a trusted authority.
81  *
82  * Note there are four conditions required for server trust. First, the
83  * public key on the certificate must be verified, which involves a
84  * number of format, content and consistency checks. Next, the server
85  * identity must be confirmed by one of four schemes: private
86  * certificate, IFF scheme, GQ scheme or certificate trail hike to a
87  * self signed trusted certificate. Finally, the server signature must
88  * be verified.
89  */
90 /*
91  * Cryptodefines
92  */
93 #define TAI_1972        10      /* initial TAI offset (s) */
94 #define MAX_LEAP        100     /* max UTC leapseconds (s) */
95 #define VALUE_LEN       (6 * 4) /* min response field length */
96 #define YEAR            (60 * 60 * 24 * 365) /* seconds in year */
97
98 /*
99  * Global cryptodata in host byte order
100  */
101 u_int32 crypto_flags = 0x0;     /* status word */
102
103 /*
104  * Global cryptodata in network byte order
105  */
106 struct cert_info *cinfo = NULL; /* certificate info/value */
107 struct value hostval;           /* host value */
108 struct value pubkey;            /* public key */
109 struct value tai_leap;          /* leapseconds table */
110 EVP_PKEY *iffpar_pkey = NULL;   /* IFF parameters */
111 EVP_PKEY *gqpar_pkey = NULL;    /* GQ parameters */
112 EVP_PKEY *mvpar_pkey = NULL;    /* MV parameters */
113 char    *iffpar_file = NULL; /* IFF parameters file */
114 char    *gqpar_file = NULL;     /* GQ parameters file */
115 char    *mvpar_file = NULL;     /* MV parameters file */
116
117 /*
118  * Private cryptodata in host byte order
119  */
120 static char *passwd = NULL;     /* private key password */
121 static EVP_PKEY *host_pkey = NULL; /* host key */
122 static EVP_PKEY *sign_pkey = NULL; /* sign key */
123 static const EVP_MD *sign_digest = NULL; /* sign digest */
124 static u_int sign_siglen;       /* sign key length */
125 static char *rand_file = NULL;  /* random seed file */
126 static char *host_file = NULL;  /* host key file */
127 static char *sign_file = NULL;  /* sign key file */
128 static char *cert_file = NULL;  /* certificate file */
129 static char *leap_file = NULL;  /* leapseconds file */
130 static tstamp_t if_fstamp = 0;  /* IFF filestamp */
131 static tstamp_t gq_fstamp = 0;  /* GQ file stamp */
132 static tstamp_t mv_fstamp = 0;  /* MV filestamp */
133 static u_int ident_scheme = 0;  /* server identity scheme */
134
135 /*
136  * Cryptotypes
137  */
138 static  int     crypto_verify   P((struct exten *, struct value *,
139                                     struct peer *));
140 static  int     crypto_encrypt  P((struct exten *, struct value *,
141                                     keyid_t *));
142 static  int     crypto_alice    P((struct peer *, struct value *));
143 static  int     crypto_alice2   P((struct peer *, struct value *));
144 static  int     crypto_alice3   P((struct peer *, struct value *));
145 static  int     crypto_bob      P((struct exten *, struct value *));
146 static  int     crypto_bob2     P((struct exten *, struct value *));
147 static  int     crypto_bob3     P((struct exten *, struct value *));
148 static  int     crypto_iff      P((struct exten *, struct peer *));
149 static  int     crypto_gq       P((struct exten *, struct peer *));
150 static  int     crypto_mv       P((struct exten *, struct peer *));
151 static  u_int   crypto_send     P((struct exten *, struct value *));
152 static  tstamp_t crypto_time    P((void));
153 static  u_long  asn2ntp         P((ASN1_TIME *));
154 static  struct cert_info *cert_parse P((u_char *, u_int, tstamp_t));
155 static  int     cert_sign       P((struct exten *, struct value *));
156 static  int     cert_valid      P((struct cert_info *, EVP_PKEY *));
157 static  int     cert_install    P((struct exten *, struct peer *));
158 static  void    cert_free       P((struct cert_info *));
159 static  EVP_PKEY *crypto_key    P((char *, tstamp_t *));
160 static  int     bighash         P((BIGNUM *, BIGNUM *));
161 static  struct cert_info *crypto_cert P((char *));
162 static  void    crypto_tai      P((char *));
163
164 #ifdef SYS_WINNT
165 int
166 readlink(char * link, char * file, int len) {
167         return (-1);
168 }
169 #endif
170
171 /*
172  * session_key - generate session key
173  *
174  * This routine generates a session key from the source address,
175  * destination address, key ID and private value. The value of the
176  * session key is the MD5 hash of these values, while the next key ID is
177  * the first four octets of the hash.
178  *
179  * Returns the next key ID
180  */
181 keyid_t
182 session_key(
183         struct sockaddr_storage *srcadr, /* source address */
184         struct sockaddr_storage *dstadr, /* destination address */
185         keyid_t keyno,          /* key ID */
186         keyid_t private,        /* private value */
187         u_long  lifetime        /* key lifetime */
188         )
189 {
190         EVP_MD_CTX ctx;         /* message digest context */
191         u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
192         keyid_t keyid;          /* key identifer */
193         u_int32 header[10];     /* data in network byte order */
194         u_int   hdlen, len;
195
196         if (!dstadr)
197                 return 0;
198         
199         /*
200          * Generate the session key and key ID. If the lifetime is
201          * greater than zero, install the key and call it trusted.
202          */
203         hdlen = 0;
204         switch(srcadr->ss_family) {
205         case AF_INET:
206                 header[0] = ((struct sockaddr_in *)srcadr)->sin_addr.s_addr;
207                 header[1] = ((struct sockaddr_in *)dstadr)->sin_addr.s_addr;
208                 header[2] = htonl(keyno);
209                 header[3] = htonl(private);
210                 hdlen = 4 * sizeof(u_int32);
211                 break;
212
213         case AF_INET6:
214                 memcpy(&header[0], &GET_INADDR6(*srcadr),
215                     sizeof(struct in6_addr));
216                 memcpy(&header[4], &GET_INADDR6(*dstadr),
217                     sizeof(struct in6_addr));
218                 header[8] = htonl(keyno);
219                 header[9] = htonl(private);
220                 hdlen = 10 * sizeof(u_int32);
221                 break;
222         }
223         EVP_DigestInit(&ctx, EVP_md5());
224         EVP_DigestUpdate(&ctx, (u_char *)header, hdlen);
225         EVP_DigestFinal(&ctx, dgst, &len);
226         memcpy(&keyid, dgst, 4);
227         keyid = ntohl(keyid);
228         if (lifetime != 0) {
229                 MD5auth_setkey(keyno, dgst, len);
230                 authtrust(keyno, lifetime);
231         }
232 #ifdef DEBUG
233         if (debug > 1)
234                 printf(
235                     "session_key: %s > %s %08x %08x hash %08x life %lu\n",
236                     stoa(srcadr), stoa(dstadr), keyno,
237                     private, keyid, lifetime);
238 #endif
239         return (keyid);
240 }
241
242
243 /*
244  * make_keylist - generate key list
245  *
246  * Returns
247  * XEVNT_OK     success
248  * XEVNT_PER    host certificate expired
249  *
250  * This routine constructs a pseudo-random sequence by repeatedly
251  * hashing the session key starting from a given source address,
252  * destination address, private value and the next key ID of the
253  * preceeding session key. The last entry on the list is saved along
254  * with its sequence number and public signature.
255  */
256 int
257 make_keylist(
258         struct peer *peer,      /* peer structure pointer */
259         struct interface *dstadr /* interface */
260         )
261 {
262         EVP_MD_CTX ctx;         /* signature context */
263         tstamp_t tstamp;        /* NTP timestamp */
264         struct autokey *ap;     /* autokey pointer */
265         struct value *vp;       /* value pointer */
266         keyid_t keyid = 0;      /* next key ID */
267         keyid_t cookie;         /* private value */
268         u_long  lifetime;
269         u_int   len, mpoll;
270         int     i;
271
272         if (!dstadr)
273                 return XEVNT_OK;
274         
275         /*
276          * Allocate the key list if necessary.
277          */
278         tstamp = crypto_time();
279         if (peer->keylist == NULL)
280                 peer->keylist = emalloc(sizeof(keyid_t) *
281                     NTP_MAXSESSION);
282
283         /*
284          * Generate an initial key ID which is unique and greater than
285          * NTP_MAXKEY.
286          */
287         while (1) {
288                 keyid = (ntp_random() + NTP_MAXKEY + 1) & ((1 <<
289                     sizeof(keyid_t)) - 1);
290                 if (authhavekey(keyid))
291                         continue;
292                 break;
293         }
294
295         /*
296          * Generate up to NTP_MAXSESSION session keys. Stop if the
297          * next one would not be unique or not a session key ID or if
298          * it would expire before the next poll. The private value
299          * included in the hash is zero if broadcast mode, the peer
300          * cookie if client mode or the host cookie if symmetric modes.
301          */
302         mpoll = 1 << min(peer->ppoll, peer->hpoll);
303         lifetime = min(sys_automax, NTP_MAXSESSION * mpoll);
304         if (peer->hmode == MODE_BROADCAST)
305                 cookie = 0;
306         else
307                 cookie = peer->pcookie;
308         for (i = 0; i < NTP_MAXSESSION; i++) {
309                 peer->keylist[i] = keyid;
310                 peer->keynumber = i;
311                 keyid = session_key(&dstadr->sin, &peer->srcadr, keyid,
312                     cookie, lifetime);
313                 lifetime -= mpoll;
314                 if (auth_havekey(keyid) || keyid <= NTP_MAXKEY ||
315                     lifetime <= mpoll)
316                         break;
317         }
318
319         /*
320          * Save the last session key ID, sequence number and timestamp,
321          * then sign these values for later retrieval by the clients. Be
322          * careful not to use invalid key media. Use the public values
323          * timestamp as filestamp. 
324          */
325         vp = &peer->sndval;
326         if (vp->ptr == NULL)
327                 vp->ptr = emalloc(sizeof(struct autokey));
328         ap = (struct autokey *)vp->ptr;
329         ap->seq = htonl(peer->keynumber);
330         ap->key = htonl(keyid);
331         vp->tstamp = htonl(tstamp);
332         vp->fstamp = hostval.tstamp;
333         vp->vallen = htonl(sizeof(struct autokey));
334         vp->siglen = 0;
335         if (tstamp != 0) {
336                 if (tstamp < cinfo->first || tstamp > cinfo->last)
337                         return (XEVNT_PER);
338
339                 if (vp->sig == NULL)
340                         vp->sig = emalloc(sign_siglen);
341                 EVP_SignInit(&ctx, sign_digest);
342                 EVP_SignUpdate(&ctx, (u_char *)vp, 12);
343                 EVP_SignUpdate(&ctx, vp->ptr, sizeof(struct autokey));
344                 if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
345                         vp->siglen = htonl(len);
346                 else
347                         msyslog(LOG_ERR, "make_keys %s\n",
348                             ERR_error_string(ERR_get_error(), NULL));
349                 peer->flags |= FLAG_ASSOC;
350         }
351 #ifdef DEBUG
352         if (debug)
353                 printf("make_keys: %d %08x %08x ts %u fs %u poll %d\n",
354                     ntohl(ap->seq), ntohl(ap->key), cookie,
355                     ntohl(vp->tstamp), ntohl(vp->fstamp), peer->hpoll);
356 #endif
357         return (XEVNT_OK);
358 }
359
360
361 /*
362  * crypto_recv - parse extension fields
363  *
364  * This routine is called when the packet has been matched to an
365  * association and passed sanity, format and MAC checks. We believe the
366  * extension field values only if the field has proper format and
367  * length, the timestamp and filestamp are valid and the signature has
368  * valid length and is verified. There are a few cases where some values
369  * are believed even if the signature fails, but only if the proventic
370  * bit is not set.
371  */
372 int
373 crypto_recv(
374         struct peer *peer,      /* peer structure pointer */
375         struct recvbuf *rbufp   /* packet buffer pointer */
376         )
377 {
378         const EVP_MD *dp;       /* message digest algorithm */
379         u_int32 *pkt;           /* receive packet pointer */
380         struct autokey *ap, *bp; /* autokey pointer */
381         struct exten *ep, *fp;  /* extension pointers */
382         int     has_mac;        /* length of MAC field */
383         int     authlen;        /* offset of MAC field */
384         associd_t associd;      /* association ID */
385         tstamp_t tstamp = 0;    /* timestamp */
386         tstamp_t fstamp = 0;    /* filestamp */
387         u_int   len;            /* extension field length */
388         u_int   code;           /* extension field opcode */
389         u_int   vallen = 0;     /* value length */
390         X509    *cert;          /* X509 certificate */
391         char    statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
392         keyid_t cookie;         /* crumbles */
393         int     hismode;        /* packet mode */
394         int     rval = XEVNT_OK;
395         u_char  *ptr;
396         u_int32 temp32;
397
398         /*
399          * Initialize. Note that the packet has already been checked for
400          * valid format and extension field lengths. First extract the
401          * field length, command code and association ID in host byte
402          * order. These are used with all commands and modes. Then check
403          * the version number, which must be 2, and length, which must
404          * be at least 8 for requests and VALUE_LEN (24) for responses.
405          * Packets that fail either test sink without a trace. The
406          * association ID is saved only if nonzero.
407          */
408         authlen = LEN_PKT_NOMAC;
409         hismode = (int)PKT_MODE((&rbufp->recv_pkt)->li_vn_mode);
410         while ((has_mac = rbufp->recv_length - authlen) > MAX_MAC_LEN) {
411                 pkt = (u_int32 *)&rbufp->recv_pkt + authlen / 4;
412                 ep = (struct exten *)pkt;
413                 code = ntohl(ep->opcode) & 0xffff0000;
414                 len = ntohl(ep->opcode) & 0x0000ffff;
415                 associd = (associd_t) ntohl(pkt[1]);
416                 rval = XEVNT_OK;
417 #ifdef DEBUG
418                 if (debug)
419                         printf(
420                             "crypto_recv: flags 0x%x ext offset %d len %u code 0x%x assocID %d\n",
421                             peer->crypto, authlen, len, code >> 16,
422                             associd);
423 #endif
424
425                 /*
426                  * Check version number and field length. If bad,
427                  * quietly ignore the packet.
428                  */
429                 if (((code >> 24) & 0x3f) != CRYPTO_VN || len < 8) {
430                         sys_unknownversion++;
431                         code |= CRYPTO_ERROR;
432                 }
433
434                 /*
435                  * Little vulnerability bandage here. If a perp tosses a
436                  * fake association ID over the fence, we better toss it
437                  * out. Only the first one counts.
438                  */
439                 if (code & CRYPTO_RESP) {
440                         if (peer->assoc == 0)
441                                 peer->assoc = associd;
442                         else if (peer->assoc != associd)
443                                 code |= CRYPTO_ERROR;
444                 }
445                 if (len >= VALUE_LEN) {
446                         tstamp = ntohl(ep->tstamp);
447                         fstamp = ntohl(ep->fstamp);
448                         vallen = ntohl(ep->vallen);
449                 }
450                 switch (code) {
451
452                 /*
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.
461                  */
462                 case CRYPTO_ASSOC:
463
464                         /*
465                          * If the machine is running when this message
466                          * arrives, the other fellow has reset and so
467                          * must we. Otherwise, pass the extension field
468                          * to the transmit side.
469                          */
470                         if (peer->crypto) {
471                                 rval = XEVNT_ERR;
472                                 break;
473                         }
474                         fp = emalloc(len);
475                         memcpy(fp, ep, len);
476                         temp32 = CRYPTO_RESP;
477                         fp->opcode |= htonl(temp32);
478                         peer->cmmd = fp;
479                         /* fall through */
480
481                 case CRYPTO_ASSOC | CRYPTO_RESP:
482
483                         /*
484                          * Discard the message if it has already been
485                          * stored or the message has been amputated.
486                          */
487                         if (peer->crypto)
488                                 break;
489
490                         if (vallen == 0 || vallen > MAXHOSTNAME ||
491                             len < VALUE_LEN + vallen) {
492                                 rval = XEVNT_LEN;
493                                 break;
494                         }
495
496                         /*
497                          * Check the identity schemes are compatible. If
498                          * the client has PC, the server must have PC,
499                          * in which case the server public key and
500                          * identity are presumed valid, so we skip the
501                          * certificate and identity exchanges and move
502                          * immediately to the cookie exchange which
503                          * confirms the server signature.
504                          */
505 #ifdef DEBUG
506                         if (debug)
507                                 printf(
508                                     "crypto_recv: ident host 0x%x server 0x%x\n",
509                                     crypto_flags, fstamp);
510 #endif
511                         temp32 = (crypto_flags | ident_scheme) &
512                             fstamp & CRYPTO_FLAG_MASK;
513                         if (crypto_flags & CRYPTO_FLAG_PRIV) {
514                                 if (!(fstamp & CRYPTO_FLAG_PRIV)) {
515                                         rval = XEVNT_KEY;
516                                         break;
517
518                                 } else {
519                                         fstamp |= CRYPTO_FLAG_VALID |
520                                             CRYPTO_FLAG_VRFY |
521                                             CRYPTO_FLAG_SIGN;
522                                 }
523                         /*
524                          * In symmetric modes it is an error if either
525                          * peer requests identity and the other peer
526                          * does not support it.
527                          */
528                         } else if ((hismode == MODE_ACTIVE || hismode ==
529                             MODE_PASSIVE) && ((crypto_flags | fstamp) &
530                             CRYPTO_FLAG_MASK) && !temp32) {
531                                 rval = XEVNT_KEY;
532                                 break;
533                         /*
534                          * It is an error if the client requests
535                          * identity and the server does not support it.
536                          */
537                         } else if (hismode == MODE_CLIENT && (fstamp &
538                             CRYPTO_FLAG_MASK) && !temp32) {
539                                 rval = XEVNT_KEY;
540                                 break;
541                         }
542
543                         /*
544                          * Otherwise, the identity scheme(s) are those
545                          * that both client and server support.
546                          */
547                         fstamp = temp32 | (fstamp & ~CRYPTO_FLAG_MASK);
548
549                         /*
550                          * Discard the message if the signature digest
551                          * NID is not supported.
552                          */
553                         temp32 = (fstamp >> 16) & 0xffff;
554                         dp =
555                             (const EVP_MD *)EVP_get_digestbynid(temp32);
556                         if (dp == NULL) {
557                                 rval = XEVNT_MD;
558                                 break;
559                         }
560
561                         /*
562                          * Save status word, host name and message
563                          * digest/signature type.
564                          */
565                         peer->crypto = fstamp;
566                         peer->digest = dp;
567                         peer->subject = emalloc(vallen + 1);
568                         memcpy(peer->subject, ep->pkt, vallen);
569                         peer->subject[vallen] = '\0';
570                         peer->issuer = emalloc(vallen + 1);
571                         strcpy(peer->issuer, peer->subject);
572                         temp32 = (fstamp >> 16) & 0xffff;
573                         snprintf(statstr, NTP_MAXSTRLEN,
574                             "flags 0x%x host %s signature %s", fstamp,
575                             peer->subject, OBJ_nid2ln(temp32));
576                         record_crypto_stats(&peer->srcadr, statstr);
577 #ifdef DEBUG
578                         if (debug)
579                                 printf("crypto_recv: %s\n", statstr);
580 #endif
581                         break;
582
583                 /*
584                  * Decode X509 certificate in ASN.1 format and extract
585                  * the data containing, among other things, subject
586                  * name and public key. In the default identification
587                  * scheme, the certificate trail is followed to a self
588                  * signed trusted certificate.
589                  */
590                 case CRYPTO_CERT | CRYPTO_RESP:
591
592                         /*
593                          * Discard the message if invalid.
594                          */
595                         if ((rval = crypto_verify(ep, NULL, peer)) !=
596                             XEVNT_OK)
597                                 break;
598
599                         /*
600                          * Scan the certificate list to delete old
601                          * versions and link the newest version first on
602                          * the list.
603                          */
604                         if ((rval = cert_install(ep, peer)) != XEVNT_OK)
605                                 break;
606
607                         /*
608                          * If we snatch the certificate before the
609                          * server certificate has been signed by its
610                          * server, it will be self signed. When it is,
611                          * we chase the certificate issuer, which the
612                          * server has, and keep going until a self
613                          * signed trusted certificate is found. Be sure
614                          * to update the issuer field, since it may
615                          * change.
616                          */
617                         if (peer->issuer != NULL)
618                                 free(peer->issuer);
619                         peer->issuer = emalloc(strlen(cinfo->issuer) +
620                             1);
621                         strcpy(peer->issuer, cinfo->issuer);
622
623                         /*
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.
629                          */
630                         if (peer->pkey == NULL) {
631                                 ptr = (u_char *)cinfo->cert.ptr;
632                                 cert = d2i_X509(NULL, &ptr,
633                                     ntohl(cinfo->cert.vallen));
634                                 peer->pkey = X509_get_pubkey(cert);
635                                 X509_free(cert);
636                         }
637                         peer->flash &= ~TEST8;
638                         temp32 = cinfo->nid;
639                         snprintf(statstr, NTP_MAXSTRLEN,
640                             "cert %s 0x%x %s (%u) fs %u",
641                             cinfo->subject, cinfo->flags,
642                             OBJ_nid2ln(temp32), temp32,
643                             ntohl(ep->fstamp));
644                         record_crypto_stats(&peer->srcadr, statstr);
645 #ifdef DEBUG
646                         if (debug)
647                                 printf("crypto_recv: %s\n", statstr);
648 #endif
649                         break;
650
651                 /*
652                  * Schnorr (IFF)identity scheme. This scheme is designed
653                  * for use with shared secret group keys and where the
654                  * certificate may be generated by a third party. The
655                  * client sends a challenge to the server, which
656                  * performs a calculation and returns the result. A
657                  * positive result is possible only if both client and
658                  * server contain the same secret group key.
659                  */
660                 case CRYPTO_IFF | CRYPTO_RESP:
661
662                         /*
663                          * Discard the message if invalid or certificate
664                          * trail not trusted.
665                          */
666                         if (!(peer->crypto & CRYPTO_FLAG_VALID)) {
667                                 rval = XEVNT_ERR;
668                                 break;
669                         }
670                         if ((rval = crypto_verify(ep, NULL, peer)) !=
671                             XEVNT_OK)
672                                 break;
673
674                         /*
675                          * If the the challenge matches the response,
676                          * the certificate public key, as well as the
677                          * server public key, signatyre and identity are
678                          * all verified at the same time. The server is
679                          * declared trusted, so we skip further
680                          * certificate stages and move immediately to
681                          * the cookie stage.
682                          */
683                         if ((rval = crypto_iff(ep, peer)) != XEVNT_OK)
684                                 break;
685
686                         peer->crypto |= CRYPTO_FLAG_VRFY |
687                             CRYPTO_FLAG_PROV;
688                         peer->flash &= ~TEST8;
689                         snprintf(statstr, NTP_MAXSTRLEN, "iff fs %u",
690                             ntohl(ep->fstamp));
691                         record_crypto_stats(&peer->srcadr, statstr);
692 #ifdef DEBUG
693                         if (debug)
694                                 printf("crypto_recv: %s\n", statstr);
695 #endif
696                         break;
697
698                 /*
699                  * Guillou-Quisquater (GQ) identity scheme. This scheme
700                  * is designed for use with public certificates carrying
701                  * the GQ public key in an extension field. The client
702                  * sends a challenge to the server, which performs a
703                  * calculation and returns the result. A positive result
704                  * is possible only if both client and server contain
705                  * the same group key and the server has the matching GQ
706                  * private key.
707                  */
708                 case CRYPTO_GQ | CRYPTO_RESP:
709
710                         /*
711                          * Discard the message if invalid or certificate
712                          * trail not trusted.
713                          */
714                         if (!(peer->crypto & CRYPTO_FLAG_VALID)) {
715                                 rval = XEVNT_ERR;
716                                 break;
717                         }
718                         if ((rval = crypto_verify(ep, NULL, peer)) !=
719                             XEVNT_OK)
720                                 break;
721
722                         /*
723                          * If the the challenge matches the response,
724                          * the certificate public key, as well as the
725                          * server public key, signatyre and identity are
726                          * all verified at the same time. The server is
727                          * declared trusted, so we skip further
728                          * certificate stages and move immediately to
729                          * the cookie stage.
730                          */
731                         if ((rval = crypto_gq(ep, peer)) != XEVNT_OK)
732                                 break;
733
734                         peer->crypto |= CRYPTO_FLAG_VRFY |
735                             CRYPTO_FLAG_PROV;
736                         peer->flash &= ~TEST8;
737                         snprintf(statstr, NTP_MAXSTRLEN, "gq fs %u",
738                             ntohl(ep->fstamp));
739                         record_crypto_stats(&peer->srcadr, statstr);
740 #ifdef DEBUG
741                         if (debug)
742                                 printf("crypto_recv: %s\n", statstr);
743 #endif
744                         break;
745
746                 /*
747                  * MV
748                  */
749                 case CRYPTO_MV | CRYPTO_RESP:
750
751                         /*
752                          * Discard the message if invalid or certificate
753                          * trail not trusted.
754                          */
755                         if (!(peer->crypto & CRYPTO_FLAG_VALID)) {
756                                 rval = XEVNT_ERR;
757                                 break;
758                         }
759                         if ((rval = crypto_verify(ep, NULL, peer)) !=
760                             XEVNT_OK)
761                                 break;
762
763                         /*
764                          * If the the challenge matches the response,
765                          * the certificate public key, as well as the
766                          * server public key, signatyre and identity are
767                          * all verified at the same time. The server is
768                          * declared trusted, so we skip further
769                          * certificate stages and move immediately to
770                          * the cookie stage.
771                          */
772                         if ((rval = crypto_mv(ep, peer)) != XEVNT_OK)
773                                 break;
774
775                         peer->crypto |= CRYPTO_FLAG_VRFY |
776                             CRYPTO_FLAG_PROV;
777                         peer->flash &= ~TEST8;
778                         snprintf(statstr, NTP_MAXSTRLEN, "mv fs %u",
779                             ntohl(ep->fstamp));
780                         record_crypto_stats(&peer->srcadr, statstr);
781 #ifdef DEBUG
782                         if (debug)
783                                 printf("crypto_recv: %s\n", statstr);
784 #endif
785                         break;
786
787                 /*
788                  * Cookie request in symmetric modes. Roll a random
789                  * cookie and install in symmetric mode. Encrypt for the
790                  * response, which is transmitted later.
791                  */
792                 case CRYPTO_COOK:
793
794                         /*
795                          * Discard the message if invalid or certificate
796                          * trail not trusted.
797                          */
798                         if (!(peer->crypto & CRYPTO_FLAG_VALID)) {
799                                 rval = XEVNT_ERR;
800                                 break;
801                         }
802                         if ((rval = crypto_verify(ep, NULL, peer)) !=
803                             XEVNT_OK)
804                                 break;
805
806                         /*
807                          * Pass the extension field to the transmit
808                          * side. If already agreed, walk away.
809                          */
810                         fp = emalloc(len);
811                         memcpy(fp, ep, len);
812                         temp32 = CRYPTO_RESP;
813                         fp->opcode |= htonl(temp32);
814                         peer->cmmd = fp;
815                         if (peer->crypto & CRYPTO_FLAG_AGREE) {
816                                 peer->flash &= ~TEST8;
817                                 break;
818                         }
819
820                         /*
821                          * Install cookie values and light the cookie
822                          * bit. The transmit side will pick up and
823                          * encrypt it for the response.
824                          */
825                         key_expire(peer);
826                         peer->cookval.tstamp = ep->tstamp;
827                         peer->cookval.fstamp = ep->fstamp;
828                         RAND_bytes((u_char *)&peer->pcookie, 4);
829                         peer->crypto &= ~CRYPTO_FLAG_AUTO;
830                         peer->crypto |= CRYPTO_FLAG_AGREE;
831                         peer->flash &= ~TEST8;
832                         snprintf(statstr, NTP_MAXSTRLEN, "cook %x ts %u fs %u",
833                             peer->pcookie, ntohl(ep->tstamp),
834                             ntohl(ep->fstamp));
835                         record_crypto_stats(&peer->srcadr, statstr);
836 #ifdef DEBUG
837                         if (debug)
838                                 printf("crypto_recv: %s\n", statstr);
839 #endif
840                         break;
841
842                 /*
843                  * Cookie response in client and symmetric modes. If the
844                  * cookie bit is set, the working cookie is the EXOR of
845                  * the current and new values.
846                  */
847                 case CRYPTO_COOK | CRYPTO_RESP:
848
849                         /*
850                          * Discard the message if invalid or identity
851                          * not confirmed or signature not verified with
852                          * respect to the cookie values.
853                          */
854                         if (!(peer->crypto & CRYPTO_FLAG_VRFY)) {
855                                 rval = XEVNT_ERR;
856                                 break;
857                         }
858                         if ((rval = crypto_verify(ep, &peer->cookval,
859                             peer)) != XEVNT_OK)
860                                 break;
861
862                         /*
863                          * Decrypt the cookie, hunting all the time for
864                          * errors.
865                          */
866                         if (vallen == (u_int) EVP_PKEY_size(host_pkey)) {
867                                 RSA_private_decrypt(vallen,
868                                     (u_char *)ep->pkt,
869                                     (u_char *)&temp32,
870                                     host_pkey->pkey.rsa,
871                                     RSA_PKCS1_OAEP_PADDING);
872                                 cookie = ntohl(temp32);
873                         } else {
874                                 rval = XEVNT_CKY;
875                                 break;
876                         }
877
878                         /*
879                          * Install cookie values and light the cookie
880                          * bit. If this is not broadcast client mode, we
881                          * are done here.
882                          */
883                         key_expire(peer);
884                         peer->cookval.tstamp = ep->tstamp;
885                         peer->cookval.fstamp = ep->fstamp;
886                         if (peer->crypto & CRYPTO_FLAG_AGREE)
887                                 peer->pcookie ^= cookie;
888                         else
889                                 peer->pcookie = cookie;
890                         if (peer->hmode == MODE_CLIENT &&
891                             !(peer->cast_flags & MDF_BCLNT))
892                                 peer->crypto |= CRYPTO_FLAG_AUTO;
893                         else
894                                 peer->crypto &= ~CRYPTO_FLAG_AUTO;
895                         peer->crypto |= CRYPTO_FLAG_AGREE;
896                         peer->flash &= ~TEST8;
897                         snprintf(statstr, NTP_MAXSTRLEN, "cook %x ts %u fs %u",
898                             peer->pcookie, ntohl(ep->tstamp),
899                             ntohl(ep->fstamp));
900                         record_crypto_stats(&peer->srcadr, statstr);
901 #ifdef DEBUG
902                         if (debug)
903                                 printf("crypto_recv: %s\n", statstr);
904 #endif
905                         break;
906
907                 /*
908                  * Install autokey values in broadcast client and
909                  * symmetric modes. We have to do this every time the
910                  * sever/peer cookie changes or a new keylist is
911                  * rolled. Ordinarily, this is automatic as this message
912                  * is piggybacked on the first NTP packet sent upon
913                  * either of these events. Note that a broadcast client
914                  * or symmetric peer can receive this response without a
915                  * matching request.
916                  */
917                 case CRYPTO_AUTO | CRYPTO_RESP:
918
919                         /*
920                          * Discard the message if invalid or identity
921                          * not confirmed or signature not verified with
922                          * respect to the receive autokey values.
923                          */
924                         if (!(peer->crypto & CRYPTO_FLAG_VRFY)) {
925                                 rval = XEVNT_ERR;
926                                 break;
927                         }
928                         if ((rval = crypto_verify(ep, &peer->recval,
929                             peer)) != XEVNT_OK)
930                                 break;
931
932                         /*
933                          * Install autokey values and light the
934                          * autokey bit. This is not hard.
935                          */
936                         if (peer->recval.ptr == NULL)
937                                 peer->recval.ptr =
938                                     emalloc(sizeof(struct autokey));
939                         bp = (struct autokey *)peer->recval.ptr;
940                         peer->recval.tstamp = ep->tstamp;
941                         peer->recval.fstamp = ep->fstamp;
942                         ap = (struct autokey *)ep->pkt;
943                         bp->seq = ntohl(ap->seq);
944                         bp->key = ntohl(ap->key);
945                         peer->pkeyid = bp->key;
946                         peer->crypto |= CRYPTO_FLAG_AUTO;
947                         peer->flash &= ~TEST8;
948                         snprintf(statstr, NTP_MAXSTRLEN,
949                             "auto seq %d key %x ts %u fs %u", bp->seq,
950                             bp->key, ntohl(ep->tstamp),
951                             ntohl(ep->fstamp));
952                         record_crypto_stats(&peer->srcadr, statstr);
953 #ifdef DEBUG
954                         if (debug)
955                                 printf("crypto_recv: %s\n", statstr);
956 #endif
957                         break;
958         
959                 /*
960                  * X509 certificate sign response. Validate the
961                  * certificate signed by the server and install. Later
962                  * this can be provided to clients of this server in
963                  * lieu of the self signed certificate in order to
964                  * validate the public key.
965                  */
966                 case CRYPTO_SIGN | CRYPTO_RESP:
967
968                         /*
969                          * Discard the message if invalid or not
970                          * proventic.
971                          */
972                         if (!(peer->crypto & CRYPTO_FLAG_PROV)) {
973                                 rval = XEVNT_ERR;
974                                 break;
975                         }
976                         if ((rval = crypto_verify(ep, NULL, peer)) !=
977                             XEVNT_OK)
978                                 break;
979
980                         /*
981                          * Scan the certificate list to delete old
982                          * versions and link the newest version first on
983                          * the list.
984                          */
985                         if ((rval = cert_install(ep, peer)) != XEVNT_OK)
986                                 break;
987
988                         peer->crypto |= CRYPTO_FLAG_SIGN;
989                         peer->flash &= ~TEST8;
990                         temp32 = cinfo->nid;
991                         snprintf(statstr, NTP_MAXSTRLEN,
992                             "sign %s 0x%x %s (%u) fs %u",
993                             cinfo->issuer, cinfo->flags,
994                             OBJ_nid2ln(temp32), temp32,
995                             ntohl(ep->fstamp));
996                         record_crypto_stats(&peer->srcadr, statstr);
997 #ifdef DEBUG
998                         if (debug)
999                                 printf("crypto_recv: %s\n", statstr);
1000 #endif
1001                         break;
1002
1003                 /*
1004                  * Install leapseconds table in symmetric modes. This
1005                  * table is proventicated to the NIST primary servers,
1006                  * either by copying the file containing the table from
1007                  * a NIST server to a trusted server or directly using
1008                  * this protocol. While the entire table is installed at
1009                  * the server, presently only the current TAI offset is
1010                  * provided via the kernel to other applications.
1011                  */
1012                 case CRYPTO_TAI:
1013
1014                         /*
1015                          * Discard the message if invalid.
1016                          */
1017                         if ((rval = crypto_verify(ep, NULL, peer)) !=
1018                             XEVNT_OK)
1019                                 break;
1020
1021                         /*
1022                          * Pass the extension field to the transmit
1023                          * side. Continue below if a leapseconds table
1024                          * accompanies the message.
1025                          */
1026                         fp = emalloc(len);
1027                         memcpy(fp, ep, len);
1028                         temp32 = CRYPTO_RESP;
1029                         fp->opcode |= htonl(temp32);
1030                         peer->cmmd = fp;
1031                         if (len <= VALUE_LEN) {
1032                                 peer->flash &= ~TEST8;
1033                                 break;
1034                         }
1035                         /* fall through */
1036
1037                 case CRYPTO_TAI | CRYPTO_RESP:
1038
1039                         /*
1040                          * If this is a response, discard the message if
1041                          * signature not verified with respect to the
1042                          * leapsecond table values.
1043                          */
1044                         if (peer->cmmd == NULL) {
1045                                 if ((rval = crypto_verify(ep,
1046                                     &peer->tai_leap, peer)) != XEVNT_OK)
1047                                         break;
1048                         }
1049
1050                         /*
1051                          * Initialize peer variables with latest update.
1052                          */
1053                         peer->tai_leap.tstamp = ep->tstamp;
1054                         peer->tai_leap.fstamp = ep->fstamp;
1055                         peer->tai_leap.vallen = ep->vallen;
1056
1057                         /*
1058                          * Install the new table if there is no stored
1059                          * table or the new table is more recent than
1060                          * the stored table. Since a filestamp may have
1061                          * changed, recompute the signatures.
1062                          */
1063                         if (ntohl(peer->tai_leap.fstamp) >
1064                             ntohl(tai_leap.fstamp)) {
1065                                 tai_leap.fstamp = ep->fstamp;
1066                                 tai_leap.vallen = ep->vallen;
1067                                 if (tai_leap.ptr != NULL)
1068                                         free(tai_leap.ptr);
1069                                 tai_leap.ptr = emalloc(vallen);
1070                                 memcpy(tai_leap.ptr, ep->pkt, vallen);
1071                                 crypto_update();
1072                         }
1073                         crypto_flags |= CRYPTO_FLAG_TAI;
1074                         peer->crypto |= CRYPTO_FLAG_LEAP;
1075                         peer->flash &= ~TEST8;
1076                         snprintf(statstr, NTP_MAXSTRLEN,
1077                             "leap %u ts %u fs %u", vallen,
1078                             ntohl(ep->tstamp), ntohl(ep->fstamp));
1079                         record_crypto_stats(&peer->srcadr, statstr);
1080 #ifdef DEBUG
1081                         if (debug)
1082                                 printf("crypto_recv: %s\n", statstr);
1083 #endif
1084                         break;
1085
1086                 /*
1087                  * We come here in symmetric modes for miscellaneous
1088                  * commands that have value fields but are processed on
1089                  * the transmit side. All we need do here is check for
1090                  * valid field length. Remaining checks are below and on
1091                  * the transmit side.
1092                  */
1093                 case CRYPTO_CERT:
1094                 case CRYPTO_IFF:
1095                 case CRYPTO_GQ:
1096                 case CRYPTO_MV:
1097                 case CRYPTO_SIGN:
1098                         if (len < VALUE_LEN) {
1099                                 rval = XEVNT_LEN;
1100                                 break;
1101                         }
1102                         /* fall through */
1103
1104                 /*
1105                  * We come here for miscellaneous requests and unknown
1106                  * requests and responses. If an unknown response or
1107                  * error, forget it. If a request, save the extension
1108                  * field for later. Unknown requests will be caught on
1109                  * the transmit side.
1110                  */
1111                 default:
1112                         if (code & (CRYPTO_RESP | CRYPTO_ERROR)) {
1113                                 rval = XEVNT_ERR;
1114                         } else if ((rval = crypto_verify(ep, NULL,
1115                             peer)) == XEVNT_OK) {
1116                                 fp = emalloc(len);
1117                                 memcpy(fp, ep, len);
1118                                 temp32 = CRYPTO_RESP;
1119                                 fp->opcode |= htonl(temp32);
1120                                 peer->cmmd = fp;
1121                         }
1122                 }
1123
1124                 /*
1125                  * We don't log length/format/timestamp errors and
1126                  * duplicates, which are log clogging vulnerabilities.
1127                  * The first error found terminates the extension field
1128                  * scan and we return the laundry to the caller. A
1129                  * length/format/timestamp error on transmit is
1130                  * cheerfully ignored, as the message is not sent.
1131                  */
1132                 if (rval > XEVNT_TSP) {
1133                         snprintf(statstr, NTP_MAXSTRLEN,
1134                             "error %x opcode %x ts %u fs %u", rval,
1135                             code, tstamp, fstamp);
1136                         record_crypto_stats(&peer->srcadr, statstr);
1137                         report_event(rval, peer);
1138 #ifdef DEBUG
1139                         if (debug)
1140                                 printf("crypto_recv: %s\n", statstr);
1141 #endif
1142                         break;
1143
1144                 } else if (rval > XEVNT_OK && (code & CRYPTO_RESP)) {
1145                         rval = XEVNT_OK;
1146                 }
1147                 authlen += len;
1148         }
1149         return (rval);
1150 }
1151
1152
1153 /*
1154  * crypto_xmit - construct extension fields
1155  *
1156  * This routine is called both when an association is configured and
1157  * when one is not. The only case where this matters is to retrieve the
1158  * autokey information, in which case the caller has to provide the
1159  * association ID to match the association.
1160  *
1161  * Returns length of extension field.
1162  */
1163 int
1164 crypto_xmit(
1165         struct pkt *xpkt,       /* transmit packet pointer */
1166         struct sockaddr_storage *srcadr_sin,    /* active runway */
1167         int     start,          /* offset to extension field */
1168         struct exten *ep,       /* extension pointer */
1169         keyid_t cookie          /* session cookie */
1170         )
1171 {
1172         u_int32 *pkt;           /* packet pointer */
1173         struct peer *peer;      /* peer structure pointer */
1174         u_int   opcode;         /* extension field opcode */
1175         struct exten *fp;       /* extension pointers */
1176         struct cert_info *cp, *xp; /* certificate info/value pointer */
1177         char    certname[MAXHOSTNAME + 1]; /* subject name buffer */
1178         char    statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1179         tstamp_t tstamp;
1180         u_int   vallen;
1181         u_int   len;
1182         struct value vtemp;
1183         associd_t associd;
1184         int     rval;
1185         keyid_t tcookie;
1186
1187         /*
1188          * Generate the requested extension field request code, length
1189          * and association ID. If this is a response and the host is not
1190          * synchronized, light the error bit and go home.
1191          */
1192         pkt = (u_int32 *)xpkt + start / 4;
1193         fp = (struct exten *)pkt;
1194         opcode = ntohl(ep->opcode);
1195         associd = (associd_t) ntohl(ep->associd);
1196         fp->associd = htonl(associd);
1197         len = 8;
1198         rval = XEVNT_OK;
1199         tstamp = crypto_time();
1200         switch (opcode & 0xffff0000) {
1201
1202         /*
1203          * Send association request and response with status word and
1204          * host name. Note, this message is not signed and the filestamp
1205          * contains only the status word.
1206          */
1207         case CRYPTO_ASSOC | CRYPTO_RESP:
1208                 len += crypto_send(fp, &hostval);
1209                 fp->fstamp = htonl(crypto_flags);
1210                 break;
1211
1212         case CRYPTO_ASSOC:
1213                 len += crypto_send(fp, &hostval);
1214                 fp->fstamp = htonl(crypto_flags | ident_scheme);
1215                 break;
1216
1217         /*
1218          * Send certificate request. Use the values from the extension
1219          * field.
1220          */
1221         case CRYPTO_CERT:
1222                 memset(&vtemp, 0, sizeof(vtemp));
1223                 vtemp.tstamp = ep->tstamp;
1224                 vtemp.fstamp = ep->fstamp;
1225                 vtemp.vallen = ep->vallen;
1226                 vtemp.ptr = (u_char *)ep->pkt;
1227                 len += crypto_send(fp, &vtemp);
1228                 break;
1229
1230         /*
1231          * Send certificate response or sign request. Use the values
1232          * from the certificate cache. If the request contains no
1233          * subject name, assume the name of this host. This is for
1234          * backwards compatibility. Private certificates are never sent.
1235          */
1236         case CRYPTO_SIGN:
1237         case CRYPTO_CERT | CRYPTO_RESP:
1238                 vallen = ntohl(ep->vallen);
1239                 if (vallen == 8) {
1240                         strcpy(certname, sys_hostname);
1241                 } else if (vallen == 0 || vallen > MAXHOSTNAME) {
1242                         rval = XEVNT_LEN;
1243                         break;
1244
1245                 } else {
1246                         memcpy(certname, ep->pkt, vallen);
1247                         certname[vallen] = '\0';
1248                 }
1249
1250                 /*
1251                  * Find all certificates with matching subject. If a
1252                  * self-signed, trusted certificate is found, use that.
1253                  * If not, use the first one with matching subject. A
1254                  * private certificate is never divulged or signed.
1255                  */
1256                 xp = NULL;
1257                 for (cp = cinfo; cp != NULL; cp = cp->link) {
1258                         if (cp->flags & CERT_PRIV)
1259                                 continue;
1260
1261                         if (strcmp(certname, cp->subject) == 0) {
1262                                 if (xp == NULL)
1263                                         xp = cp;
1264                                 if (strcmp(certname, cp->issuer) ==
1265                                     0 && cp->flags & CERT_TRUST) {
1266                                         xp = cp;
1267                                         break;
1268                                 }
1269                         }
1270                 }
1271
1272                 /*
1273                  * Be careful who you trust. If not yet synchronized,
1274                  * give back an empty response. If certificate not found
1275                  * or beyond the lifetime, return an error. This is to
1276                  * avoid a bad dude trying to get an expired certificate
1277                  * re-signed. Otherwise, send it.
1278                  *
1279                  * Note the timestamp and filestamp are taken from the
1280                  * certificate value structure. For all certificates the
1281                  * timestamp is the latest signature update time. For
1282                  * host and imported certificates the filestamp is the
1283                  * creation epoch. For signed certificates the filestamp
1284                  * is the creation epoch of the trusted certificate at
1285                  * the base of the certificate trail. In principle, this
1286                  * allows strong checking for signature masquerade.
1287                  */
1288                 if (tstamp == 0)
1289                         break;
1290
1291                 if (xp == NULL)
1292                         rval = XEVNT_CRT;
1293                 else if (tstamp < xp->first || tstamp > xp->last)
1294                         rval = XEVNT_SRV;
1295                 else
1296                         len += crypto_send(fp, &xp->cert);
1297                 break;
1298
1299         /*
1300          * Send challenge in Schnorr (IFF) identity scheme.
1301          */
1302         case CRYPTO_IFF:
1303                 if ((peer = findpeerbyassoc(ep->pkt[0])) == NULL) {
1304                         rval = XEVNT_ERR;
1305                         break;
1306                 }
1307                 if ((rval = crypto_alice(peer, &vtemp)) == XEVNT_OK) {
1308                         len += crypto_send(fp, &vtemp);
1309                         value_free(&vtemp);
1310                 }
1311                 break;
1312
1313         /*
1314          * Send response in Schnorr (IFF) identity scheme.
1315          */
1316         case CRYPTO_IFF | CRYPTO_RESP:
1317                 if ((rval = crypto_bob(ep, &vtemp)) == XEVNT_OK) {
1318                         len += crypto_send(fp, &vtemp);
1319                         value_free(&vtemp);
1320                 }
1321                 break;
1322
1323         /*
1324          * Send challenge in Guillou-Quisquater (GQ) identity scheme.
1325          */
1326         case CRYPTO_GQ:
1327                 if ((peer = findpeerbyassoc(ep->pkt[0])) == NULL) {
1328                         rval = XEVNT_ERR;
1329                         break;
1330                 }
1331                 if ((rval = crypto_alice2(peer, &vtemp)) == XEVNT_OK) {
1332                         len += crypto_send(fp, &vtemp);
1333                         value_free(&vtemp);
1334                 }
1335                 break;
1336
1337         /*
1338          * Send response in Guillou-Quisquater (GQ) identity scheme.
1339          */
1340         case CRYPTO_GQ | CRYPTO_RESP:
1341                 if ((rval = crypto_bob2(ep, &vtemp)) == XEVNT_OK) {
1342                         len += crypto_send(fp, &vtemp);
1343                         value_free(&vtemp);
1344                 }
1345                 break;
1346
1347         /*
1348          * Send challenge in MV identity scheme.
1349          */
1350         case CRYPTO_MV:
1351                 if ((peer = findpeerbyassoc(ep->pkt[0])) == NULL) {
1352                         rval = XEVNT_ERR;
1353                         break;
1354                 }
1355                 if ((rval = crypto_alice3(peer, &vtemp)) == XEVNT_OK) {
1356                         len += crypto_send(fp, &vtemp);
1357                         value_free(&vtemp);
1358                 }
1359                 break;
1360
1361         /*
1362          * Send response in MV identity scheme.
1363          */
1364         case CRYPTO_MV | CRYPTO_RESP:
1365                 if ((rval = crypto_bob3(ep, &vtemp)) == XEVNT_OK) {
1366                         len += crypto_send(fp, &vtemp);
1367                         value_free(&vtemp);
1368                 }
1369                 break;
1370
1371         /*
1372          * Send certificate sign response. The integrity of the request
1373          * certificate has already been verified on the receive side.
1374          * Sign the response using the local server key. Use the
1375          * filestamp from the request and use the timestamp as the
1376          * current time. Light the error bit if the certificate is
1377          * invalid or contains an unverified signature.
1378          */
1379         case CRYPTO_SIGN | CRYPTO_RESP:
1380                 if ((rval = cert_sign(ep, &vtemp)) == XEVNT_OK)
1381                         len += crypto_send(fp, &vtemp);
1382                 value_free(&vtemp);
1383                 break;
1384
1385         /*
1386          * Send public key and signature. Use the values from the public
1387          * key.
1388          */
1389         case CRYPTO_COOK:
1390                 len += crypto_send(fp, &pubkey);
1391                 break;
1392
1393         /*
1394          * Encrypt and send cookie and signature. Light the error bit if
1395          * anything goes wrong.
1396          */
1397         case CRYPTO_COOK | CRYPTO_RESP:
1398                 if ((opcode & 0xffff) < VALUE_LEN) {
1399                         rval = XEVNT_LEN;
1400                         break;
1401                 }
1402                 if (PKT_MODE(xpkt->li_vn_mode) == MODE_SERVER) {
1403                         tcookie = cookie;
1404                 } else {
1405                         if ((peer = findpeerbyassoc(associd)) == NULL) {
1406                                 rval = XEVNT_ERR;
1407                                 break;
1408                         }
1409                         tcookie = peer->pcookie;
1410                 }
1411                 if ((rval = crypto_encrypt(ep, &vtemp, &tcookie)) ==
1412                     XEVNT_OK)
1413                         len += crypto_send(fp, &vtemp);
1414                 value_free(&vtemp);
1415                 break;
1416
1417         /*
1418          * Find peer and send autokey data and signature in broadcast
1419          * server and symmetric modes. Use the values in the autokey
1420          * structure. If no association is found, either the server has
1421          * restarted with new associations or some perp has replayed an
1422          * old message, in which case light the error bit.
1423          */
1424         case CRYPTO_AUTO | CRYPTO_RESP:
1425                 if ((peer = findpeerbyassoc(associd)) == NULL) {
1426                         rval = XEVNT_ERR;
1427                         break;
1428                 }
1429                 peer->flags &= ~FLAG_ASSOC;
1430                 len += crypto_send(fp, &peer->sndval);
1431                 break;
1432
1433         /*
1434          * Send leapseconds table and signature. Use the values from the
1435          * tai structure. If no table has been loaded, just send an
1436          * empty request.
1437          */
1438         case CRYPTO_TAI:
1439         case CRYPTO_TAI | CRYPTO_RESP:
1440                 if (crypto_flags & CRYPTO_FLAG_TAI)
1441                         len += crypto_send(fp, &tai_leap);
1442                 break;
1443
1444         /*
1445          * Default - Fall through for requests; for unknown responses,
1446          * flag as error.
1447          */
1448         default:
1449                 if (opcode & CRYPTO_RESP)
1450                         rval = XEVNT_ERR;
1451         }
1452
1453         /*
1454          * In case of error, flame the log. If a request, toss the
1455          * puppy; if a response, return so the sender can flame, too.
1456          */
1457         if (rval != XEVNT_OK) {
1458                 opcode |= CRYPTO_ERROR;
1459                 snprintf(statstr, NTP_MAXSTRLEN,
1460                     "error %x opcode %x", rval, opcode);
1461                 record_crypto_stats(srcadr_sin, statstr);
1462                 report_event(rval, NULL);
1463 #ifdef DEBUG
1464                 if (debug)
1465                         printf("crypto_xmit: %s\n", statstr);
1466 #endif
1467                 if (!(opcode & CRYPTO_RESP))
1468                         return (0);
1469         }
1470
1471         /*
1472          * Round up the field length to a multiple of 8 bytes and save
1473          * the request code and length.
1474          */
1475         len = ((len + 7) / 8) * 8;
1476         fp->opcode = htonl((opcode & 0xffff0000) | len);
1477 #ifdef DEBUG
1478         if (debug)
1479                 printf(
1480                     "crypto_xmit: flags 0x%x ext offset %d len %u code 0x%x assocID %d\n",
1481                     crypto_flags, start, len, opcode >> 16, associd);
1482 #endif
1483         return (len);
1484 }
1485
1486
1487 /*
1488  * crypto_verify - parse and verify the extension field and value
1489  *
1490  * Returns
1491  * XEVNT_OK     success
1492  * XEVNT_LEN    bad field format or length
1493  * XEVNT_TSP    bad timestamp
1494  * XEVNT_FSP    bad filestamp
1495  * XEVNT_PUB    bad or missing public key
1496  * XEVNT_SGL    bad signature length
1497  * XEVNT_SIG    signature not verified
1498  * XEVNT_ERR    protocol error
1499  */
1500 static int
1501 crypto_verify(
1502         struct exten *ep,       /* extension pointer */
1503         struct value *vp,       /* value pointer */
1504         struct peer *peer       /* peer structure pointer */
1505         )
1506 {
1507         EVP_PKEY *pkey;         /* server public key */
1508         EVP_MD_CTX ctx;         /* signature context */
1509         tstamp_t tstamp, tstamp1 = 0; /* timestamp */
1510         tstamp_t fstamp, fstamp1 = 0; /* filestamp */
1511         u_int   vallen;         /* value length */
1512         u_int   siglen;         /* signature length */
1513         u_int   opcode, len;
1514         int     i;
1515
1516         /*
1517          * We require valid opcode and field lengths, timestamp,
1518          * filestamp, public key, digest, signature length and
1519          * signature, where relevant. Note that preliminary length
1520          * checks are done in the main loop.
1521          */
1522         len = ntohl(ep->opcode) & 0x0000ffff;
1523         opcode = ntohl(ep->opcode) & 0xffff0000;
1524
1525         /*
1526          * Check for valid operation code and protocol. The opcode must
1527          * not have the error bit set. If a response, it must have a
1528          * value header. If a request and does not contain a value
1529          * header, no need for further checking.
1530          */
1531         if (opcode & CRYPTO_ERROR)
1532                 return (XEVNT_ERR);
1533
1534         if (opcode & CRYPTO_RESP) {
1535                 if (len < VALUE_LEN)
1536                         return (XEVNT_LEN);
1537         } else {
1538                 if (len < VALUE_LEN)
1539                         return (XEVNT_OK);
1540         }
1541
1542         /*
1543          * We have a value header. Check for valid field lengths. The
1544          * field length must be long enough to contain the value header,
1545          * value and signature. Note both the value and signature fields
1546          * are rounded up to the next word.
1547          */
1548         vallen = ntohl(ep->vallen);
1549         i = (vallen + 3) / 4;
1550         siglen = ntohl(ep->pkt[i++]);
1551         if (len < VALUE_LEN + ((vallen + 3) / 4) * 4 + ((siglen + 3) /
1552             4) * 4)
1553                 return (XEVNT_LEN);
1554
1555         /*
1556          * Punt if this is a response with no data. Punt if this is a
1557          * request and a previous response is pending. 
1558          */
1559         if (opcode & CRYPTO_RESP) {
1560                 if (vallen == 0)
1561                         return (XEVNT_LEN);
1562         } else {
1563                 if (peer->cmmd != NULL)
1564                         return (XEVNT_LEN);
1565         }
1566
1567         /*
1568          * Check for valid timestamp and filestamp. If the timestamp is
1569          * zero, the sender is not synchronized and signatures are
1570          * disregarded. If not, the timestamp must not precede the
1571          * filestamp. The timestamp and filestamp must not precede the
1572          * corresponding values in the value structure, if present. Once
1573          * the autokey values have been installed, the timestamp must
1574          * always be later than the corresponding value in the value
1575          * structure. Duplicate timestamps are illegal once the cookie
1576          * has been validated.
1577          */
1578         tstamp = ntohl(ep->tstamp);
1579         fstamp = ntohl(ep->fstamp);
1580         if (tstamp == 0)
1581                 return (XEVNT_OK);
1582
1583         if (tstamp < fstamp)
1584                 return (XEVNT_TSP);
1585
1586         if (vp != NULL) {
1587                 tstamp1 = ntohl(vp->tstamp);
1588                 fstamp1 = ntohl(vp->fstamp);
1589                 if ((tstamp < tstamp1 || (tstamp == tstamp1 &&
1590                     (peer->crypto & CRYPTO_FLAG_AUTO))))
1591                         return (XEVNT_TSP);
1592
1593                 if ((tstamp < fstamp1 || fstamp < fstamp1))
1594                         return (XEVNT_FSP);
1595         }
1596
1597         /*
1598          * Check for valid signature length, public key and digest
1599          * algorithm.
1600          */
1601         if (crypto_flags & peer->crypto & CRYPTO_FLAG_PRIV)
1602                 pkey = sign_pkey;
1603         else
1604                 pkey = peer->pkey;
1605         if (siglen == 0 || pkey == NULL || peer->digest == NULL)
1606                 return (XEVNT_OK);
1607
1608         if (siglen != (u_int)EVP_PKEY_size(pkey))
1609                 return (XEVNT_SGL);
1610
1611         /*
1612          * Darn, I thought we would never get here. Verify the
1613          * signature. If the identity exchange is verified, light the
1614          * proventic bit. If no client identity scheme is specified,
1615          * avoid doing the sign exchange.
1616          */
1617         EVP_VerifyInit(&ctx, peer->digest);
1618         EVP_VerifyUpdate(&ctx, (u_char *)&ep->tstamp, vallen + 12);
1619         if (EVP_VerifyFinal(&ctx, (u_char *)&ep->pkt[i], siglen, pkey) <= 0)
1620                 return (XEVNT_SIG);
1621
1622         if (peer->crypto & CRYPTO_FLAG_VRFY) {
1623                 peer->crypto |= CRYPTO_FLAG_PROV;
1624                 if (!(crypto_flags & CRYPTO_FLAG_MASK))
1625                         peer->crypto |= CRYPTO_FLAG_SIGN;
1626         }
1627         return (XEVNT_OK);
1628 }
1629
1630
1631 /*
1632  * crypto_encrypt - construct encrypted cookie and signature from
1633  * extension field and cookie
1634  *
1635  * Returns
1636  * XEVNT_OK     success
1637  * XEVNT_PUB    bad or missing public key
1638  * XEVNT_CKY    bad or missing cookie
1639  * XEVNT_PER    host certificate expired
1640  */
1641 static int
1642 crypto_encrypt(
1643         struct exten *ep,       /* extension pointer */
1644         struct value *vp,       /* value pointer */
1645         keyid_t *cookie         /* server cookie */
1646         )
1647 {
1648         EVP_PKEY *pkey;         /* public key */
1649         EVP_MD_CTX ctx;         /* signature context */
1650         tstamp_t tstamp;        /* NTP timestamp */
1651         u_int32 temp32;
1652         u_int   len;
1653         u_char  *ptr;
1654
1655         /*
1656          * Extract the public key from the request.
1657          */
1658         len = ntohl(ep->vallen);
1659         ptr = (u_char *)ep->pkt;
1660         pkey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &ptr, len);
1661         if (pkey == NULL) {
1662                 msyslog(LOG_ERR, "crypto_encrypt %s\n",
1663                     ERR_error_string(ERR_get_error(), NULL));
1664                 return (XEVNT_PUB);
1665         }
1666
1667         /*
1668          * Encrypt the cookie, encode in ASN.1 and sign.
1669          */
1670         tstamp = crypto_time();
1671         memset(vp, 0, sizeof(struct value));
1672         vp->tstamp = htonl(tstamp);
1673         vp->fstamp = hostval.tstamp;
1674         len = EVP_PKEY_size(pkey);
1675         vp->vallen = htonl(len);
1676         vp->ptr = emalloc(len);
1677         temp32 = htonl(*cookie);
1678         if (!RSA_public_encrypt(4, (u_char *)&temp32, vp->ptr,
1679             pkey->pkey.rsa, RSA_PKCS1_OAEP_PADDING)) {
1680                 msyslog(LOG_ERR, "crypto_encrypt %s\n",
1681                     ERR_error_string(ERR_get_error(), NULL));
1682                 EVP_PKEY_free(pkey);
1683                 return (XEVNT_CKY);
1684         }
1685         EVP_PKEY_free(pkey);
1686         vp->siglen = 0;
1687         if (tstamp == 0)
1688                 return (XEVNT_OK);
1689
1690         if (tstamp < cinfo->first || tstamp > cinfo->last)
1691                 return (XEVNT_PER);
1692
1693         vp->sig = emalloc(sign_siglen);
1694         EVP_SignInit(&ctx, sign_digest);
1695         EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
1696         EVP_SignUpdate(&ctx, vp->ptr, len);
1697         if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
1698                 vp->siglen = htonl(len);
1699         return (XEVNT_OK);
1700 }
1701
1702
1703 /*
1704  * crypto_ident - construct extension field for identity scheme
1705  *
1706  * This routine determines which identity scheme is in use and
1707  * constructs an extension field for that scheme.
1708  */
1709 u_int
1710 crypto_ident(
1711         struct peer *peer       /* peer structure pointer */
1712         )
1713 {
1714         char    filename[MAXFILENAME + 1];
1715
1716         /*
1717          * If the server identity has already been verified, no further
1718          * action is necessary. Otherwise, try to load the identity file
1719          * of the certificate issuer. If the issuer file is not found,
1720          * try the host file. If nothing found, declare a cryptobust.
1721          * Note we can't get here unless the trusted certificate has
1722          * been found and the CRYPTO_FLAG_VALID bit is set, so the
1723          * certificate issuer is valid.
1724          */
1725         if (peer->ident_pkey != NULL)
1726                 EVP_PKEY_free(peer->ident_pkey);
1727         if (peer->crypto & CRYPTO_FLAG_GQ) {
1728                 snprintf(filename, MAXFILENAME, "ntpkey_gq_%s",
1729                     peer->issuer);
1730                 peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1731                 if (peer->ident_pkey != NULL)
1732                         return (CRYPTO_GQ);
1733
1734                 snprintf(filename, MAXFILENAME, "ntpkey_gq_%s",
1735                     sys_hostname);
1736                 peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1737                 if (peer->ident_pkey != NULL)
1738                         return (CRYPTO_GQ);
1739         }
1740         if (peer->crypto & CRYPTO_FLAG_IFF) {
1741                 snprintf(filename, MAXFILENAME, "ntpkey_iff_%s",
1742                     peer->issuer);
1743                 peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1744                 if (peer->ident_pkey != NULL)
1745                         return (CRYPTO_IFF);
1746
1747                 snprintf(filename, MAXFILENAME, "ntpkey_iff_%s",
1748                     sys_hostname);
1749                 peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1750                 if (peer->ident_pkey != NULL)
1751                         return (CRYPTO_IFF);
1752         }
1753         if (peer->crypto & CRYPTO_FLAG_MV) {
1754                 snprintf(filename, MAXFILENAME, "ntpkey_mv_%s",
1755                     peer->issuer);
1756                 peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1757                 if (peer->ident_pkey != NULL)
1758                         return (CRYPTO_MV);
1759
1760                 snprintf(filename, MAXFILENAME, "ntpkey_mv_%s",
1761                     sys_hostname);
1762                 peer->ident_pkey = crypto_key(filename, &peer->fstamp);
1763                 if (peer->ident_pkey != NULL)
1764                         return (CRYPTO_MV);
1765         }
1766
1767         /*
1768          * No compatible identity scheme is available. Life is hard.
1769          */
1770         msyslog(LOG_INFO,
1771             "crypto_ident: no compatible identity scheme found");
1772         return (0);
1773 }
1774
1775
1776 /*
1777  * crypto_args - construct extension field from arguments
1778  *
1779  * This routine creates an extension field with current timestamps and
1780  * specified opcode, association ID and optional string. Note that the
1781  * extension field is created here, but freed after the crypto_xmit()
1782  * call in the protocol module.
1783  *
1784  * Returns extension field pointer (no errors).
1785  */
1786 struct exten *
1787 crypto_args(
1788         struct peer *peer,      /* peer structure pointer */
1789         u_int   opcode,         /* operation code */
1790         char    *str            /* argument string */
1791         )
1792 {
1793         tstamp_t tstamp;        /* NTP timestamp */
1794         struct exten *ep;       /* extension field pointer */
1795         u_int   len;            /* extension field length */
1796
1797         tstamp = crypto_time();
1798         len = sizeof(struct exten);
1799         if (str != NULL)
1800                 len += strlen(str);
1801         ep = emalloc(len);
1802         memset(ep, 0, len);
1803         if (opcode == 0)
1804                 return (ep);
1805
1806         ep->opcode = htonl(opcode + len);
1807
1808         /*
1809          * If a response, send our ID; if a request, send the
1810          * responder's ID.
1811          */
1812         if (opcode & CRYPTO_RESP)
1813                 ep->associd = htonl(peer->associd);
1814         else
1815                 ep->associd = htonl(peer->assoc);
1816         ep->tstamp = htonl(tstamp);
1817         ep->fstamp = hostval.tstamp;
1818         ep->vallen = 0;
1819         if (str != NULL) {
1820                 ep->vallen = htonl(strlen(str));
1821                 memcpy((char *)ep->pkt, str, strlen(str));
1822         } else {
1823                 ep->pkt[0] = peer->associd;
1824         }
1825         return (ep);
1826 }
1827
1828
1829 /*
1830  * crypto_send - construct extension field from value components
1831  *
1832  * Returns extension field length. Note: it is not polite to send a
1833  * nonempty signature with zero timestamp or a nonzero timestamp with
1834  * empty signature, but these rules are not enforced here.
1835  */
1836 u_int
1837 crypto_send(
1838         struct exten *ep,       /* extension field pointer */
1839         struct value *vp        /* value pointer */
1840         )
1841 {
1842         u_int   len, temp32;
1843         int     i;
1844
1845         /*
1846          * Copy data. If the data field is empty or zero length, encode
1847          * an empty value with length zero.
1848          */
1849         ep->tstamp = vp->tstamp;
1850         ep->fstamp = vp->fstamp;
1851         ep->vallen = vp->vallen;
1852         len = 12;
1853         temp32 = ntohl(vp->vallen);
1854         if (temp32 > 0 && vp->ptr != NULL)
1855                 memcpy(ep->pkt, vp->ptr, temp32);
1856
1857         /*
1858          * Copy signature. If the signature field is empty or zero
1859          * length, encode an empty signature with length zero.
1860          */
1861         i = (temp32 + 3) / 4;
1862         len += i * 4 + 4;
1863         ep->pkt[i++] = vp->siglen;
1864         temp32 = ntohl(vp->siglen);
1865         if (temp32 > 0 && vp->sig != NULL)
1866                 memcpy(&ep->pkt[i], vp->sig, temp32);
1867         len += temp32;
1868         return (len);
1869 }
1870
1871
1872 /*
1873  * crypto_update - compute new public value and sign extension fields
1874  *
1875  * This routine runs periodically, like once a day, and when something
1876  * changes. It updates the timestamps on three value structures and one
1877  * value structure list, then signs all the structures:
1878  *
1879  * hostval      host name (not signed)
1880  * pubkey       public key
1881  * cinfo        certificate info/value list
1882  * tai_leap     leapseconds file
1883  *
1884  * Filestamps are proventicated data, so this routine is run only when
1885  * the host has been synchronized to a proventicated source. Thus, the
1886  * timestamp is proventicated, too, and can be used to deflect
1887  * clogging attacks and even cook breakfast.
1888  *
1889  * Returns void (no errors)
1890  */
1891 void
1892 crypto_update(void)
1893 {
1894         EVP_MD_CTX ctx;         /* message digest context */
1895         struct cert_info *cp, *cpn; /* certificate info/value */
1896         char    statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
1897         tstamp_t tstamp;        /* NTP timestamp */
1898         u_int   len;
1899
1900         if ((tstamp = crypto_time()) == 0)
1901                 return;
1902
1903         hostval.tstamp = htonl(tstamp);
1904
1905         /*
1906          * Sign public key and timestamps. The filestamp is derived from
1907          * the host key file extension from wherever the file was
1908          * generated. 
1909          */
1910         if (pubkey.vallen != 0) {
1911                 pubkey.tstamp = hostval.tstamp;
1912                 pubkey.siglen = 0;
1913                 if (pubkey.sig == NULL)
1914                         pubkey.sig = emalloc(sign_siglen);
1915                 EVP_SignInit(&ctx, sign_digest);
1916                 EVP_SignUpdate(&ctx, (u_char *)&pubkey, 12);
1917                 EVP_SignUpdate(&ctx, pubkey.ptr, ntohl(pubkey.vallen));
1918                 if (EVP_SignFinal(&ctx, pubkey.sig, &len, sign_pkey))
1919                         pubkey.siglen = htonl(len);
1920         }
1921
1922         /*
1923          * Sign certificates and timestamps. The filestamp is derived
1924          * from the certificate file extension from wherever the file
1925          * was generated. Note we do not throw expired certificates
1926          * away; they may have signed younger ones.
1927          */
1928         for (cp = cinfo; cp != NULL; cp = cpn) {
1929                 cpn = cp->link;
1930                 cp->cert.tstamp = hostval.tstamp;
1931                 cp->cert.siglen = 0;
1932                 if (cp->cert.sig == NULL)
1933                         cp->cert.sig = emalloc(sign_siglen);
1934                 EVP_SignInit(&ctx, sign_digest);
1935                 EVP_SignUpdate(&ctx, (u_char *)&cp->cert, 12);
1936                 EVP_SignUpdate(&ctx, cp->cert.ptr,
1937                     ntohl(cp->cert.vallen));
1938                 if (EVP_SignFinal(&ctx, cp->cert.sig, &len, sign_pkey))
1939                         cp->cert.siglen = htonl(len);
1940         }
1941
1942         /*
1943          * Sign leapseconds table and timestamps. The filestamp is
1944          * derived from the leapsecond file extension from wherever the
1945          * file was generated.
1946          */
1947         if (tai_leap.vallen != 0) {
1948                 tai_leap.tstamp = hostval.tstamp;
1949                 tai_leap.siglen = 0;
1950                 if (tai_leap.sig == NULL)
1951                         tai_leap.sig = emalloc(sign_siglen);
1952                 EVP_SignInit(&ctx, sign_digest);
1953                 EVP_SignUpdate(&ctx, (u_char *)&tai_leap, 12);
1954                 EVP_SignUpdate(&ctx, tai_leap.ptr,
1955                     ntohl(tai_leap.vallen));
1956                 if (EVP_SignFinal(&ctx, tai_leap.sig, &len, sign_pkey))
1957                         tai_leap.siglen = htonl(len);
1958         }
1959         snprintf(statstr, NTP_MAXSTRLEN,
1960             "update ts %u", ntohl(hostval.tstamp)); 
1961         record_crypto_stats(NULL, statstr);
1962 #ifdef DEBUG
1963         if (debug)
1964                 printf("crypto_update: %s\n", statstr);
1965 #endif
1966 }
1967
1968
1969 /*
1970  * value_free - free value structure components.
1971  *
1972  * Returns void (no errors)
1973  */
1974 void
1975 value_free(
1976         struct value *vp        /* value structure */
1977         )
1978 {
1979         if (vp->ptr != NULL)
1980                 free(vp->ptr);
1981         if (vp->sig != NULL)
1982                 free(vp->sig);
1983         memset(vp, 0, sizeof(struct value));
1984 }
1985
1986
1987 /*
1988  * crypto_time - returns current NTP time in seconds.
1989  */
1990 tstamp_t
1991 crypto_time()
1992 {
1993         l_fp    tstamp;         /* NTP time */  L_CLR(&tstamp);
1994
1995         L_CLR(&tstamp);
1996         if (sys_leap != LEAP_NOTINSYNC)
1997                 get_systime(&tstamp);
1998         return (tstamp.l_ui);
1999 }
2000
2001
2002 /*
2003  * asn2ntp - convert ASN1_TIME time structure to NTP time in seconds.
2004  */
2005 u_long
2006 asn2ntp (
2007         ASN1_TIME *asn1time     /* pointer to ASN1_TIME structure */
2008         )
2009 {
2010         char    *v;             /* pointer to ASN1_TIME string */
2011         struct  tm tm;          /* used to convert to NTP time */
2012
2013         /*
2014          * Extract time string YYMMDDHHMMSSZ from ASN1 time structure.
2015          * Note that the YY, MM, DD fields start with one, the HH, MM,
2016          * SS fiels start with zero and the Z character should be 'Z'
2017          * for UTC. Also note that years less than 50 map to years
2018          * greater than 100. Dontcha love ASN.1? Better than MIL-188.
2019          */
2020         if (asn1time->length > 13)
2021                 return ((u_long)(~0));  /* We can't use -1 here. It's invalid */
2022
2023         v = (char *)asn1time->data;
2024         tm.tm_year = (v[0] - '0') * 10 + v[1] - '0';
2025         if (tm.tm_year < 50)
2026                 tm.tm_year += 100;
2027         tm.tm_mon = (v[2] - '0') * 10 + v[3] - '0' - 1;
2028         tm.tm_mday = (v[4] - '0') * 10 + v[5] - '0';
2029         tm.tm_hour = (v[6] - '0') * 10 + v[7] - '0';
2030         tm.tm_min = (v[8] - '0') * 10 + v[9] - '0';
2031         tm.tm_sec = (v[10] - '0') * 10 + v[11] - '0';
2032         tm.tm_wday = 0;
2033         tm.tm_yday = 0;
2034         tm.tm_isdst = 0;
2035         return (timegm(&tm) + JAN_1970);
2036 }
2037
2038
2039 /*
2040  * bigdig() - compute a BIGNUM MD5 hash of a BIGNUM number.
2041  */
2042 static int
2043 bighash(
2044         BIGNUM  *bn,            /* BIGNUM * from */
2045         BIGNUM  *bk             /* BIGNUM * to */
2046         )
2047 {
2048         EVP_MD_CTX ctx;         /* message digest context */
2049         u_char dgst[EVP_MAX_MD_SIZE]; /* message digest */
2050         u_char  *ptr;           /* a BIGNUM as binary string */
2051         u_int   len;
2052
2053         len = BN_num_bytes(bn);
2054         ptr = emalloc(len);
2055         BN_bn2bin(bn, ptr);
2056         EVP_DigestInit(&ctx, EVP_md5());
2057         EVP_DigestUpdate(&ctx, ptr, len);
2058         EVP_DigestFinal(&ctx, dgst, &len);
2059         BN_bin2bn(dgst, len, bk);
2060
2061         /* XXX MEMLEAK? free ptr? */
2062
2063         return (1);
2064 }
2065
2066
2067 /*
2068  ***********************************************************************
2069  *                                                                     *
2070  * The following routines implement the Schnorr (IFF) identity scheme  *
2071  *                                                                     *
2072  ***********************************************************************
2073  *
2074  * The Schnorr (IFF) identity scheme is intended for use when
2075  * the ntp-genkeys program does not generate the certificates used in
2076  * the protocol and the group key cannot be conveyed in the certificate
2077  * itself. For this purpose, new generations of IFF values must be
2078  * securely transmitted to all members of the group before use. The
2079  * scheme is self contained and independent of new generations of host
2080  * keys, sign keys and certificates.
2081  *
2082  * The IFF identity scheme is based on DSA cryptography and algorithms
2083  * described in Stinson p. 285. The IFF values hide in a DSA cuckoo
2084  * structure, but only the primes and generator are used. The p is a
2085  * 512-bit prime, q a 160-bit prime that divides p - 1 and is a qth root
2086  * of 1 mod p; that is, g^q = 1 mod p. The TA rolls primvate random
2087  * group key b disguised as a DSA structure member, then computes public
2088  * key g^(q - b). These values are shared only among group members and
2089  * never revealed in messages. Alice challenges Bob to confirm identity
2090  * using the protocol described below.
2091  *
2092  * How it works
2093  *
2094  * The scheme goes like this. Both Alice and Bob have the public primes
2095  * p, q and generator g. The TA gives private key b to Bob and public
2096  * key v = g^(q - a) mod p to Alice.
2097  *
2098  * Alice rolls new random challenge r and sends to Bob in the IFF
2099  * request message. Bob rolls new random k, then computes y = k + b r
2100  * mod q and x = g^k mod p and sends (y, hash(x)) to Alice in the
2101  * response message. Besides making the response shorter, the hash makes
2102  * it effectivey impossible for an intruder to solve for b by observing
2103  * a number of these messages.
2104  * 
2105  * Alice receives the response and computes g^y v^r mod p. After a bit
2106  * of algebra, this simplifies to g^k. If the hash of this result
2107  * matches hash(x), Alice knows that Bob has the group key b. The signed
2108  * response binds this knowledge to Bob's private key and the public key
2109  * previously received in his certificate.
2110  *
2111  * crypto_alice - construct Alice's challenge in IFF scheme
2112  *
2113  * Returns
2114  * XEVNT_OK     success
2115  * XEVNT_PUB    bad or missing public key
2116  * XEVNT_ID     bad or missing group key
2117  */
2118 static int
2119 crypto_alice(
2120         struct peer *peer,      /* peer pointer */
2121         struct value *vp        /* value pointer */
2122         )
2123 {
2124         DSA     *dsa;           /* IFF parameters */
2125         BN_CTX  *bctx;          /* BIGNUM context */
2126         EVP_MD_CTX ctx;         /* signature context */
2127         tstamp_t tstamp;
2128         u_int   len;
2129
2130         /*
2131          * The identity parameters must have correct format and content.
2132          */
2133         if (peer->ident_pkey == NULL)
2134                 return (XEVNT_ID);
2135
2136         if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
2137                 msyslog(LOG_INFO, "crypto_alice: defective key");
2138                 return (XEVNT_PUB);
2139         }
2140
2141         /*
2142          * Roll new random r (0 < r < q). The OpenSSL library has a bug
2143          * omitting BN_rand_range, so we have to do it the hard way.
2144          */
2145         bctx = BN_CTX_new();
2146         len = BN_num_bytes(dsa->q);
2147         if (peer->iffval != NULL)
2148                 BN_free(peer->iffval);
2149         peer->iffval = BN_new();
2150         BN_rand(peer->iffval, len * 8, -1, 1);  /* r */
2151         BN_mod(peer->iffval, peer->iffval, dsa->q, bctx);
2152         BN_CTX_free(bctx);
2153
2154         /*
2155          * Sign and send to Bob. The filestamp is from the local file.
2156          */
2157         tstamp = crypto_time();
2158         memset(vp, 0, sizeof(struct value));
2159         vp->tstamp = htonl(tstamp);
2160         vp->fstamp = htonl(peer->fstamp);
2161         vp->vallen = htonl(len);
2162         vp->ptr = emalloc(len);
2163         BN_bn2bin(peer->iffval, vp->ptr);
2164         vp->siglen = 0;
2165         if (tstamp == 0)
2166                 return (XEVNT_OK);
2167
2168         if (tstamp < cinfo->first || tstamp > cinfo->last)
2169                 return (XEVNT_PER);
2170
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(len);
2177         return (XEVNT_OK);
2178 }
2179
2180
2181 /*
2182  * crypto_bob - construct Bob's response to Alice's challenge
2183  *
2184  * Returns
2185  * XEVNT_OK     success
2186  * XEVNT_ID     bad or missing group key
2187  * XEVNT_ERR    protocol error
2188  * XEVNT_PER    host expired certificate
2189  */
2190 static int
2191 crypto_bob(
2192         struct exten *ep,       /* extension pointer */
2193         struct value *vp        /* value pointer */
2194         )
2195 {
2196         DSA     *dsa;           /* IFF parameters */
2197         DSA_SIG *sdsa;          /* DSA signature context fake */
2198         BN_CTX  *bctx;          /* BIGNUM context */
2199         EVP_MD_CTX ctx;         /* signature context */
2200         tstamp_t tstamp;        /* NTP timestamp */
2201         BIGNUM  *bn, *bk, *r;
2202         u_char  *ptr;
2203         u_int   len;
2204
2205         /*
2206          * If the IFF parameters are not valid, something awful
2207          * happened or we are being tormented.
2208          */
2209         if (iffpar_pkey == NULL) {
2210                 msyslog(LOG_INFO, "crypto_bob: scheme unavailable");
2211                 return (XEVNT_ID);
2212         }
2213         dsa = iffpar_pkey->pkey.dsa;
2214
2215         /*
2216          * Extract r from the challenge.
2217          */
2218         len = ntohl(ep->vallen);
2219         if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2220                 msyslog(LOG_ERR, "crypto_bob %s\n",
2221                     ERR_error_string(ERR_get_error(), NULL));
2222                 return (XEVNT_ERR);
2223         }
2224
2225         /*
2226          * Bob rolls random k (0 < k < q), computes y = k + b r mod q
2227          * and x = g^k mod p, then sends (y, hash(x)) to Alice.
2228          */
2229         bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2230         sdsa = DSA_SIG_new();
2231         BN_rand(bk, len * 8, -1, 1);            /* k */
2232         BN_mod_mul(bn, dsa->priv_key, r, dsa->q, bctx); /* b r mod q */
2233         BN_add(bn, bn, bk);
2234         BN_mod(bn, bn, dsa->q, bctx);           /* k + b r mod q */
2235         sdsa->r = BN_dup(bn);
2236         BN_mod_exp(bk, dsa->g, bk, dsa->p, bctx); /* g^k mod p */
2237         bighash(bk, bk);
2238         sdsa->s = BN_dup(bk);
2239         BN_CTX_free(bctx);
2240         BN_free(r); BN_free(bn); BN_free(bk);
2241
2242         /*
2243          * Encode the values in ASN.1 and sign.
2244          */
2245         tstamp = crypto_time();
2246         memset(vp, 0, sizeof(struct value));
2247         vp->tstamp = htonl(tstamp);
2248         vp->fstamp = htonl(if_fstamp);
2249         len = i2d_DSA_SIG(sdsa, NULL);
2250         if (len <= 0) {
2251                 msyslog(LOG_ERR, "crypto_bob %s\n",
2252                     ERR_error_string(ERR_get_error(), NULL));
2253                 DSA_SIG_free(sdsa);
2254                 return (XEVNT_ERR);
2255         }
2256         vp->vallen = htonl(len);
2257         ptr = emalloc(len);
2258         vp->ptr = ptr;
2259         i2d_DSA_SIG(sdsa, &ptr);
2260         DSA_SIG_free(sdsa);
2261         vp->siglen = 0;
2262         if (tstamp == 0)
2263                 return (XEVNT_OK);
2264
2265         if (tstamp < cinfo->first || tstamp > cinfo->last)
2266                 return (XEVNT_PER);
2267
2268         vp->sig = emalloc(sign_siglen);
2269         EVP_SignInit(&ctx, sign_digest);
2270         EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2271         EVP_SignUpdate(&ctx, vp->ptr, len);
2272         if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2273                 vp->siglen = htonl(len);
2274         return (XEVNT_OK);
2275 }
2276
2277
2278 /*
2279  * crypto_iff - verify Bob's response to Alice's challenge
2280  *
2281  * Returns
2282  * XEVNT_OK     success
2283  * XEVNT_PUB    bad or missing public key
2284  * XEVNT_ID     bad or missing group key
2285  * XEVNT_FSP    bad filestamp
2286  */
2287 int
2288 crypto_iff(
2289         struct exten *ep,       /* extension pointer */
2290         struct peer *peer       /* peer structure pointer */
2291         )
2292 {
2293         DSA     *dsa;           /* IFF parameters */
2294         BN_CTX  *bctx;          /* BIGNUM context */
2295         DSA_SIG *sdsa;          /* DSA parameters */
2296         BIGNUM  *bn, *bk;
2297         u_int   len;
2298         const u_char    *ptr;
2299         int     temp;
2300
2301         /*
2302          * If the IFF parameters are not valid or no challenge was sent,
2303          * something awful happened or we are being tormented.
2304          */
2305         if (peer->ident_pkey == NULL) {
2306                 msyslog(LOG_INFO, "crypto_iff: scheme unavailable");
2307                 return (XEVNT_ID);
2308         }
2309         if (ntohl(ep->fstamp) != peer->fstamp) {
2310                 msyslog(LOG_INFO, "crypto_iff: invalid filestamp %u",
2311                     ntohl(ep->fstamp));
2312                 return (XEVNT_FSP);
2313         }
2314         if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
2315                 msyslog(LOG_INFO, "crypto_iff: defective key");
2316                 return (XEVNT_PUB);
2317         }
2318         if (peer->iffval == NULL) {
2319                 msyslog(LOG_INFO, "crypto_iff: missing challenge");
2320                 return (XEVNT_ID);
2321         }
2322
2323         /*
2324          * Extract the k + b r and g^k values from the response.
2325          */
2326         bctx = BN_CTX_new(); bk = BN_new(); bn = BN_new();
2327         len = ntohl(ep->vallen);
2328         ptr = (const u_char *)ep->pkt;
2329         if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2330                 msyslog(LOG_ERR, "crypto_iff %s\n",
2331                     ERR_error_string(ERR_get_error(), NULL));
2332                 return (XEVNT_ERR);
2333         }
2334
2335         /*
2336          * Compute g^(k + b r) g^(q - b)r mod p.
2337          */
2338         BN_mod_exp(bn, dsa->pub_key, peer->iffval, dsa->p, bctx);
2339         BN_mod_exp(bk, dsa->g, sdsa->r, dsa->p, bctx);
2340         BN_mod_mul(bn, bn, bk, dsa->p, bctx);
2341
2342         /*
2343          * Verify the hash of the result matches hash(x).
2344          */
2345         bighash(bn, bn);
2346         temp = BN_cmp(bn, sdsa->s);
2347         BN_free(bn); BN_free(bk); BN_CTX_free(bctx);
2348         BN_free(peer->iffval);
2349         peer->iffval = NULL;
2350         DSA_SIG_free(sdsa);
2351         if (temp == 0)
2352                 return (XEVNT_OK);
2353
2354         else
2355                 return (XEVNT_ID);
2356 }
2357
2358
2359 /*
2360  ***********************************************************************
2361  *                                                                     *
2362  * The following routines implement the Guillou-Quisquater (GQ)        *
2363  * identity scheme                                                     *
2364  *                                                                     *
2365  ***********************************************************************
2366  *
2367  * The Guillou-Quisquater (GQ) identity scheme is intended for use when
2368  * the ntp-genkeys program generates the certificates used in the
2369  * protocol and the group key can be conveyed in a certificate extension
2370  * field. The scheme is self contained and independent of new
2371  * generations of host keys, sign keys and certificates.
2372  *
2373  * The GQ identity scheme is based on RSA cryptography and algorithms
2374  * described in Stinson p. 300 (with errors). The GQ values hide in a
2375  * RSA cuckoo structure, but only the modulus is used. The 512-bit
2376  * public modulus is n = p q, where p and q are secret large primes. The
2377  * TA rolls random group key b disguised as a RSA structure member.
2378  * Except for the public key, these values are shared only among group
2379  * members and never revealed in messages.
2380  *
2381  * When rolling new certificates, Bob recomputes the private and
2382  * public keys. The private key u is a random roll, while the public key
2383  * is the inverse obscured by the group key v = (u^-1)^b. These values
2384  * replace the private and public keys normally generated by the RSA
2385  * scheme. Alice challenges Bob to confirm identity using the protocol
2386  * described below.
2387  *
2388  * How it works
2389  *
2390  * The scheme goes like this. Both Alice and Bob have the same modulus n
2391  * and some random b as the group key. These values are computed and
2392  * distributed in advance via secret means, although only the group key
2393  * b is truly secret. Each has a private random private key u and public
2394  * key (u^-1)^b, although not necessarily the same ones. Bob and Alice
2395  * can regenerate the key pair from time to time without affecting
2396  * operations. The public key is conveyed on the certificate in an
2397  * extension field; the private key is never revealed.
2398  *
2399  * Alice rolls new random challenge r and sends to Bob in the GQ
2400  * request message. Bob rolls new random k, then computes y = k u^r mod
2401  * n and x = k^b mod n and sends (y, hash(x)) to Alice in the response
2402  * message. Besides making the response shorter, the hash makes it
2403  * effectivey impossible for an intruder to solve for b by observing
2404  * a number of these messages.
2405  * 
2406  * Alice receives the response and computes y^b v^r mod n. After a bit
2407  * of algebra, this simplifies to k^b. If the hash of this result
2408  * matches hash(x), Alice knows that Bob has the group key b. The signed
2409  * response binds this knowledge to Bob's private key and the public key
2410  * previously received in his certificate.
2411  *
2412  * crypto_alice2 - construct Alice's challenge in GQ scheme
2413  *
2414  * Returns
2415  * XEVNT_OK     success
2416  * XEVNT_PUB    bad or missing public key
2417  * XEVNT_ID     bad or missing group key
2418  * XEVNT_PER    host certificate expired
2419  */
2420 static int
2421 crypto_alice2(
2422         struct peer *peer,      /* peer pointer */
2423         struct value *vp        /* value pointer */
2424         )
2425 {
2426         RSA     *rsa;           /* GQ parameters */
2427         BN_CTX  *bctx;          /* BIGNUM context */
2428         EVP_MD_CTX ctx;         /* signature context */
2429         tstamp_t tstamp;
2430         u_int   len;
2431
2432         /*
2433          * The identity parameters must have correct format and content.
2434          */
2435         if (peer->ident_pkey == NULL)
2436                 return (XEVNT_ID);
2437
2438         if ((rsa = peer->ident_pkey->pkey.rsa) == NULL) {
2439                 msyslog(LOG_INFO, "crypto_alice2: defective key");
2440                 return (XEVNT_PUB);
2441         }
2442
2443         /*
2444          * Roll new random r (0 < r < n). The OpenSSL library has a bug
2445          * omitting BN_rand_range, so we have to do it the hard way.
2446          */
2447         bctx = BN_CTX_new();
2448         len = BN_num_bytes(rsa->n);
2449         if (peer->iffval != NULL)
2450                 BN_free(peer->iffval);
2451         peer->iffval = BN_new();
2452         BN_rand(peer->iffval, len * 8, -1, 1);  /* r mod n */
2453         BN_mod(peer->iffval, peer->iffval, rsa->n, bctx);
2454         BN_CTX_free(bctx);
2455
2456         /*
2457          * Sign and send to Bob. The filestamp is from the local file.
2458          */
2459         tstamp = crypto_time();
2460         memset(vp, 0, sizeof(struct value));
2461         vp->tstamp = htonl(tstamp);
2462         vp->fstamp = htonl(peer->fstamp);
2463         vp->vallen = htonl(len);
2464         vp->ptr = emalloc(len);
2465         BN_bn2bin(peer->iffval, vp->ptr);
2466         vp->siglen = 0;
2467         if (tstamp == 0)
2468                 return (XEVNT_OK);
2469
2470         if (tstamp < cinfo->first || tstamp > cinfo->last)
2471                 return (XEVNT_PER);
2472
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(len);
2479         return (XEVNT_OK);
2480 }
2481
2482
2483 /*
2484  * crypto_bob2 - construct Bob's response to Alice's challenge
2485  *
2486  * Returns
2487  * XEVNT_OK     success
2488  * XEVNT_ID     bad or missing group key
2489  * XEVNT_ERR    protocol error
2490  * XEVNT_PER    host certificate expired
2491  */
2492 static int
2493 crypto_bob2(
2494         struct exten *ep,       /* extension pointer */
2495         struct value *vp        /* value pointer */
2496         )
2497 {
2498         RSA     *rsa;           /* GQ parameters */
2499         DSA_SIG *sdsa;          /* DSA parameters */
2500         BN_CTX  *bctx;          /* BIGNUM context */
2501         EVP_MD_CTX ctx;         /* signature context */
2502         tstamp_t tstamp;        /* NTP timestamp */
2503         BIGNUM  *r, *k, *g, *y;
2504         u_char  *ptr;
2505         u_int   len;
2506
2507         /*
2508          * If the GQ parameters are not valid, something awful
2509          * happened or we are being tormented.
2510          */
2511         if (gqpar_pkey == NULL) {
2512                 msyslog(LOG_INFO, "crypto_bob2: scheme unavailable");
2513                 return (XEVNT_ID);
2514         }
2515         rsa = gqpar_pkey->pkey.rsa;
2516
2517         /*
2518          * Extract r from the challenge.
2519          */
2520         len = ntohl(ep->vallen);
2521         if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2522                 msyslog(LOG_ERR, "crypto_bob2 %s\n",
2523                     ERR_error_string(ERR_get_error(), NULL));
2524                 return (XEVNT_ERR);
2525         }
2526
2527         /*
2528          * Bob rolls random k (0 < k < n), computes y = k u^r mod n and
2529          * x = k^b mod n, then sends (y, hash(x)) to Alice. 
2530          */
2531         bctx = BN_CTX_new(); k = BN_new(); g = BN_new(); y = BN_new();
2532         sdsa = DSA_SIG_new();
2533         BN_rand(k, len * 8, -1, 1);             /* k */
2534         BN_mod(k, k, rsa->n, bctx);
2535         BN_mod_exp(y, rsa->p, r, rsa->n, bctx); /* u^r mod n */
2536         BN_mod_mul(y, k, y, rsa->n, bctx);      /* k u^r mod n */
2537         sdsa->r = BN_dup(y);
2538         BN_mod_exp(g, k, rsa->e, rsa->n, bctx); /* k^b mod n */
2539         bighash(g, g);
2540         sdsa->s = BN_dup(g);
2541         BN_CTX_free(bctx);
2542         BN_free(r); BN_free(k); BN_free(g); BN_free(y);
2543  
2544         /*
2545          * Encode the values in ASN.1 and sign.
2546          */
2547         tstamp = crypto_time();
2548         memset(vp, 0, sizeof(struct value));
2549         vp->tstamp = htonl(tstamp);
2550         vp->fstamp = htonl(gq_fstamp);
2551         len = i2d_DSA_SIG(sdsa, NULL);
2552         if (len <= 0) {
2553                 msyslog(LOG_ERR, "crypto_bob2 %s\n",
2554                     ERR_error_string(ERR_get_error(), NULL));
2555                 DSA_SIG_free(sdsa);
2556                 return (XEVNT_ERR);
2557         }
2558         vp->vallen = htonl(len);
2559         ptr = emalloc(len);
2560         vp->ptr = ptr;
2561         i2d_DSA_SIG(sdsa, &ptr);
2562         DSA_SIG_free(sdsa);
2563         vp->siglen = 0;
2564         if (tstamp == 0)
2565                 return (XEVNT_OK);
2566
2567         if (tstamp < cinfo->first || tstamp > cinfo->last)
2568                 return (XEVNT_PER);
2569
2570         vp->sig = emalloc(sign_siglen);
2571         EVP_SignInit(&ctx, sign_digest);
2572         EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2573         EVP_SignUpdate(&ctx, vp->ptr, len);
2574         if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2575                 vp->siglen = htonl(len);
2576         return (XEVNT_OK);
2577 }
2578
2579
2580 /*
2581  * crypto_gq - verify Bob's response to Alice's challenge
2582  *
2583  * Returns
2584  * XEVNT_OK     success
2585  * XEVNT_PUB    bad or missing public key
2586  * XEVNT_ID     bad or missing group keys
2587  * XEVNT_ERR    protocol error
2588  * XEVNT_FSP    bad filestamp
2589  */
2590 int
2591 crypto_gq(
2592         struct exten *ep,       /* extension pointer */
2593         struct peer *peer       /* peer structure pointer */
2594         )
2595 {
2596         RSA     *rsa;           /* GQ parameters */
2597         BN_CTX  *bctx;          /* BIGNUM context */
2598         DSA_SIG *sdsa;          /* RSA signature context fake */
2599         BIGNUM  *y, *v;
2600         const u_char    *ptr;
2601         u_int   len;
2602         int     temp;
2603
2604         /*
2605          * If the GQ parameters are not valid or no challenge was sent,
2606          * something awful happened or we are being tormented.
2607          */
2608         if (peer->ident_pkey == NULL) {
2609                 msyslog(LOG_INFO, "crypto_gq: scheme unavailable");
2610                 return (XEVNT_ID);
2611         }
2612         if (ntohl(ep->fstamp) != peer->fstamp) {
2613                 msyslog(LOG_INFO, "crypto_gq: invalid filestamp %u",
2614                     ntohl(ep->fstamp));
2615                 return (XEVNT_FSP);
2616         }
2617         if ((rsa = peer->ident_pkey->pkey.rsa) == NULL) {
2618                 msyslog(LOG_INFO, "crypto_gq: defective key");
2619                 return (XEVNT_PUB);
2620         }
2621         if (peer->iffval == NULL) {
2622                 msyslog(LOG_INFO, "crypto_gq: missing challenge");
2623                 return (XEVNT_ID);
2624         }
2625
2626         /*
2627          * Extract the y = k u^r and hash(x = k^b) values from the
2628          * response.
2629          */
2630         bctx = BN_CTX_new(); y = BN_new(); v = BN_new();
2631         len = ntohl(ep->vallen);
2632         ptr = (const u_char *)ep->pkt;
2633         if ((sdsa = d2i_DSA_SIG(NULL, &ptr, len)) == NULL) {
2634                 msyslog(LOG_ERR, "crypto_gq %s\n",
2635                     ERR_error_string(ERR_get_error(), NULL));
2636                 return (XEVNT_ERR);
2637         }
2638
2639         /*
2640          * Compute v^r y^b mod n.
2641          */
2642         BN_mod_exp(v, peer->grpkey, peer->iffval, rsa->n, bctx);
2643                                                 /* v^r mod n */
2644         BN_mod_exp(y, sdsa->r, rsa->e, rsa->n, bctx); /* y^b mod n */
2645         BN_mod_mul(y, v, y, rsa->n, bctx);      /* v^r y^b mod n */
2646
2647         /*
2648          * Verify the hash of the result matches hash(x).
2649          */
2650         bighash(y, y);
2651         temp = BN_cmp(y, sdsa->s);
2652         BN_CTX_free(bctx); BN_free(y); BN_free(v);
2653         BN_free(peer->iffval);
2654         peer->iffval = NULL;
2655         DSA_SIG_free(sdsa);
2656         if (temp == 0)
2657                 return (XEVNT_OK);
2658
2659         else
2660                 return (XEVNT_ID);
2661 }
2662
2663
2664 /*
2665  ***********************************************************************
2666  *                                                                     *
2667  * The following routines implement the Mu-Varadharajan (MV) identity  *
2668  * scheme                                                              *
2669  *                                                                     *
2670  ***********************************************************************
2671  */
2672 /*
2673  * The Mu-Varadharajan (MV) cryptosystem was originally intended when
2674  * servers broadcast messages to clients, but clients never send
2675  * messages to servers. There is one encryption key for the server and a
2676  * separate decryption key for each client. It operated something like a
2677  * pay-per-view satellite broadcasting system where the session key is
2678  * encrypted by the broadcaster and the decryption keys are held in a
2679  * tamperproof set-top box.
2680  *
2681  * The MV parameters and private encryption key hide in a DSA cuckoo
2682  * structure which uses the same parameters, but generated in a
2683  * different way. The values are used in an encryption scheme similar to
2684  * El Gamal cryptography and a polynomial formed from the expansion of
2685  * product terms (x - x[j]), as described in Mu, Y., and V.
2686  * Varadharajan: Robust and Secure Broadcasting, Proc. Indocrypt 2001,
2687  * 223-231. The paper has significant errors and serious omissions.
2688  *
2689  * Let q be the product of n distinct primes s'[j] (j = 1...n), where
2690  * each s'[j] has m significant bits. Let p be a prime p = 2 * q + 1, so
2691  * that q and each s'[j] divide p - 1 and p has M = n * m + 1
2692  * significant bits. The elements x mod q of Zq with the elements 2 and
2693  * the primes removed form a field Zq* valid for polynomial arithetic.
2694  * Let g be a generator of Zp; that is, gcd(g, p - 1) = 1 and g^q = 1
2695  * mod p. We expect M to be in the 500-bit range and n relatively small,
2696  * like 25, so the likelihood of a randomly generated element of x mod q
2697  * of Zq colliding with a factor of p - 1 is very small and can be
2698  * avoided. Associated with each s'[j] is an element s[j] such that s[j]
2699  * s'[j] = s'[j] mod q. We find s[j] as the quotient (q + s'[j]) /
2700  * s'[j]. These are the parameters of the scheme and they are expensive
2701  * to compute.
2702  *
2703  * We set up an instance of the scheme as follows. A set of random
2704  * values x[j] mod q (j = 1...n), are generated as the zeros of a
2705  * polynomial of order n. The product terms (x - x[j]) are expanded to
2706  * form coefficients a[i] mod q (i = 0...n) in powers of x. These are
2707  * used as exponents of the generator g mod p to generate the private
2708  * encryption key A. The pair (gbar, ghat) of public server keys and the
2709  * pairs (xbar[j], xhat[j]) (j = 1...n) of private client keys are used
2710  * to construct the decryption keys. The devil is in the details.
2711  *
2712  * The distinguishing characteristic of this scheme is the capability to
2713  * revoke keys. Included in the calculation of E, gbar and ghat is the
2714  * product s = prod(s'[j]) (j = 1...n) above. If the factor s'[j] is
2715  * subsequently removed from the product and E, gbar and ghat
2716  * recomputed, the jth client will no longer be able to compute E^-1 and
2717  * thus unable to decrypt the block.
2718  *
2719  * How it works
2720  *
2721  * The scheme goes like this. Bob has the server values (p, A, q, gbar,
2722  * ghat) and Alice the client values (p, xbar, xhat).
2723  *
2724  * Alice rolls new random challenge r (0 < r < p) and sends to Bob in
2725  * the MV request message. Bob rolls new random k (0 < k < q), encrypts
2726  * y = A^k mod p (a permutation) and sends (hash(y), gbar^k, ghat^k) to
2727  * Alice.
2728  * 
2729  * Alice receives the response and computes the decryption key (the
2730  * inverse permutation) from previously obtained (xbar, xhat) and
2731  * (gbar^k, ghat^k) in the message. She computes the inverse, which is
2732  * unique by reasons explained in the ntp-keygen.c program sources. If
2733  * the hash of this result matches hash(y), Alice knows that Bob has the
2734  * group key b. The signed response binds this knowledge to Bob's
2735  * private key and the public key previously received in his
2736  * certificate.
2737  *
2738  * crypto_alice3 - construct Alice's challenge in MV scheme
2739  *
2740  * Returns
2741  * XEVNT_OK     success
2742  * XEVNT_PUB    bad or missing public key
2743  * XEVNT_ID     bad or missing group key
2744  * XEVNT_PER    host certificate expired
2745  */
2746 static int
2747 crypto_alice3(
2748         struct peer *peer,      /* peer pointer */
2749         struct value *vp        /* value pointer */
2750         )
2751 {
2752         DSA     *dsa;           /* MV parameters */
2753         BN_CTX  *bctx;          /* BIGNUM context */
2754         EVP_MD_CTX ctx;         /* signature context */
2755         tstamp_t tstamp;
2756         u_int   len;
2757
2758         /*
2759          * The identity parameters must have correct format and content.
2760          */
2761         if (peer->ident_pkey == NULL)
2762                 return (XEVNT_ID);
2763
2764         if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
2765                 msyslog(LOG_INFO, "crypto_alice3: defective key");
2766                 return (XEVNT_PUB);
2767         }
2768
2769         /*
2770          * Roll new random r (0 < r < q). The OpenSSL library has a bug
2771          * omitting BN_rand_range, so we have to do it the hard way.
2772          */
2773         bctx = BN_CTX_new();
2774         len = BN_num_bytes(dsa->p);
2775         if (peer->iffval != NULL)
2776                 BN_free(peer->iffval);
2777         peer->iffval = BN_new();
2778         BN_rand(peer->iffval, len * 8, -1, 1);  /* r */
2779         BN_mod(peer->iffval, peer->iffval, dsa->p, bctx);
2780         BN_CTX_free(bctx);
2781
2782         /*
2783          * Sign and send to Bob. The filestamp is from the local file.
2784          */
2785         tstamp = crypto_time();
2786         memset(vp, 0, sizeof(struct value));
2787         vp->tstamp = htonl(tstamp);
2788         vp->fstamp = htonl(peer->fstamp);
2789         vp->vallen = htonl(len);
2790         vp->ptr = emalloc(len);
2791         BN_bn2bin(peer->iffval, vp->ptr);
2792         vp->siglen = 0;
2793         if (tstamp == 0)
2794                 return (XEVNT_OK);
2795
2796         if (tstamp < cinfo->first || tstamp > cinfo->last)
2797                 return (XEVNT_PER);
2798
2799         vp->sig = emalloc(sign_siglen);
2800         EVP_SignInit(&ctx, sign_digest);
2801         EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2802         EVP_SignUpdate(&ctx, vp->ptr, len);
2803         if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2804                 vp->siglen = htonl(len);
2805         return (XEVNT_OK);
2806 }
2807
2808
2809 /*
2810  * crypto_bob3 - construct Bob's response to Alice's challenge
2811  *
2812  * Returns
2813  * XEVNT_OK     success
2814  * XEVNT_ERR    protocol error
2815  * XEVNT_PER    host certificate expired
2816  */
2817 static int
2818 crypto_bob3(
2819         struct exten *ep,       /* extension pointer */
2820         struct value *vp        /* value pointer */
2821         )
2822 {
2823         DSA     *dsa;           /* MV parameters */
2824         DSA     *sdsa;          /* DSA signature context fake */
2825         BN_CTX  *bctx;          /* BIGNUM context */
2826         EVP_MD_CTX ctx;         /* signature context */
2827         tstamp_t tstamp;        /* NTP timestamp */
2828         BIGNUM  *r, *k, *u;
2829         u_char  *ptr;
2830         u_int   len;
2831
2832         /*
2833          * If the MV parameters are not valid, something awful
2834          * happened or we are being tormented.
2835          */
2836         if (mvpar_pkey == NULL) {
2837                 msyslog(LOG_INFO, "crypto_bob3: scheme unavailable");
2838                 return (XEVNT_ID);
2839         }
2840         dsa = mvpar_pkey->pkey.dsa;
2841
2842         /*
2843          * Extract r from the challenge.
2844          */
2845         len = ntohl(ep->vallen);
2846         if ((r = BN_bin2bn((u_char *)ep->pkt, len, NULL)) == NULL) {
2847                 msyslog(LOG_ERR, "crypto_bob3 %s\n",
2848                     ERR_error_string(ERR_get_error(), NULL));
2849                 return (XEVNT_ERR);
2850         }
2851
2852         /*
2853          * Bob rolls random k (0 < k < q), making sure it is not a
2854          * factor of q. He then computes y = A^k r and sends (hash(y),
2855          * gbar^k, ghat^k) to Alice.
2856          */
2857         bctx = BN_CTX_new(); k = BN_new(); u = BN_new();
2858         sdsa = DSA_new();
2859         sdsa->p = BN_new(); sdsa->q = BN_new(); sdsa->g = BN_new();
2860         while (1) {
2861                 BN_rand(k, BN_num_bits(dsa->q), 0, 0);
2862                 BN_mod(k, k, dsa->q, bctx);
2863                 BN_gcd(u, k, dsa->q, bctx);
2864                 if (BN_is_one(u))
2865                         break;
2866         }
2867         BN_mod_exp(u, dsa->g, k, dsa->p, bctx); /* A r */
2868         BN_mod_mul(u, u, r, dsa->p, bctx);
2869         bighash(u, sdsa->p);
2870         BN_mod_exp(sdsa->q, dsa->priv_key, k, dsa->p, bctx); /* gbar */
2871         BN_mod_exp(sdsa->g, dsa->pub_key, k, dsa->p, bctx); /* ghat */
2872         BN_CTX_free(bctx); BN_free(k); BN_free(r); BN_free(u);
2873
2874         /*
2875          * Encode the values in ASN.1 and sign.
2876          */
2877         tstamp = crypto_time();
2878         memset(vp, 0, sizeof(struct value));
2879         vp->tstamp = htonl(tstamp);
2880         vp->fstamp = htonl(mv_fstamp);
2881         len = i2d_DSAparams(sdsa, NULL);
2882         if (len <= 0) {
2883                 msyslog(LOG_ERR, "crypto_bob3 %s\n",
2884                     ERR_error_string(ERR_get_error(), NULL));
2885                 DSA_free(sdsa);
2886                 return (XEVNT_ERR);
2887         }
2888         vp->vallen = htonl(len);
2889         ptr = emalloc(len);
2890         vp->ptr = ptr;
2891         i2d_DSAparams(sdsa, &ptr);
2892         DSA_free(sdsa);
2893         vp->siglen = 0;
2894         if (tstamp == 0)
2895                 return (XEVNT_OK);
2896
2897         if (tstamp < cinfo->first || tstamp > cinfo->last)
2898                 return (XEVNT_PER);
2899
2900         vp->sig = emalloc(sign_siglen);
2901         EVP_SignInit(&ctx, sign_digest);
2902         EVP_SignUpdate(&ctx, (u_char *)&vp->tstamp, 12);
2903         EVP_SignUpdate(&ctx, vp->ptr, len);
2904         if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
2905                 vp->siglen = htonl(len);
2906         return (XEVNT_OK);
2907 }
2908
2909
2910 /*
2911  * crypto_mv - verify Bob's response to Alice's challenge
2912  *
2913  * Returns
2914  * XEVNT_OK     success
2915  * XEVNT_PUB    bad or missing public key
2916  * XEVNT_ID     bad or missing group key
2917  * XEVNT_ERR    protocol error
2918  * XEVNT_FSP    bad filestamp
2919  */
2920 int
2921 crypto_mv(
2922         struct exten *ep,       /* extension pointer */
2923         struct peer *peer       /* peer structure pointer */
2924         )
2925 {
2926         DSA     *dsa;           /* MV parameters */
2927         DSA     *sdsa;          /* DSA parameters */
2928         BN_CTX  *bctx;          /* BIGNUM context */
2929         BIGNUM  *k, *u, *v;
2930         u_int   len;
2931         const u_char    *ptr;
2932         int     temp;
2933
2934         /*
2935          * If the MV parameters are not valid or no challenge was sent,
2936          * something awful happened or we are being tormented.
2937          */
2938         if (peer->ident_pkey == NULL) {
2939                 msyslog(LOG_INFO, "crypto_mv: scheme unavailable");
2940                 return (XEVNT_ID);
2941         }
2942         if (ntohl(ep->fstamp) != peer->fstamp) {
2943                 msyslog(LOG_INFO, "crypto_mv: invalid filestamp %u",
2944                     ntohl(ep->fstamp));
2945                 return (XEVNT_FSP);
2946         }
2947         if ((dsa = peer->ident_pkey->pkey.dsa) == NULL) {
2948                 msyslog(LOG_INFO, "crypto_mv: defective key");
2949                 return (XEVNT_PUB);
2950         }
2951         if (peer->iffval == NULL) {
2952                 msyslog(LOG_INFO, "crypto_mv: missing challenge");
2953                 return (XEVNT_ID);
2954         }
2955
2956         /*
2957          * Extract the (hash(y), gbar, ghat) values from the response.
2958          */
2959         bctx = BN_CTX_new(); k = BN_new(); u = BN_new(); v = BN_new();
2960         len = ntohl(ep->vallen);
2961         ptr = (const u_char *)ep->pkt;
2962         if ((sdsa = d2i_DSAparams(NULL, &ptr, len)) == NULL) {
2963                 msyslog(LOG_ERR, "crypto_mv %s\n",
2964                     ERR_error_string(ERR_get_error(), NULL));
2965                 return (XEVNT_ERR);
2966         }
2967
2968         /*
2969          * Compute (gbar^xhat ghat^xbar)^-1 mod p.
2970          */
2971         BN_mod_exp(u, sdsa->q, dsa->pub_key, dsa->p, bctx);
2972         BN_mod_exp(v, sdsa->g, dsa->priv_key, dsa->p, bctx);
2973         BN_mod_mul(u, u, v, dsa->p, bctx);
2974         BN_mod_inverse(u, u, dsa->p, bctx);
2975         BN_mod_mul(v, u, peer->iffval, dsa->p, bctx);
2976
2977         /*
2978          * The result should match the hash of r mod p.
2979          */
2980         bighash(v, v);
2981         temp = BN_cmp(v, sdsa->p);
2982         BN_CTX_free(bctx); BN_free(k); BN_free(u); BN_free(v);
2983         BN_free(peer->iffval);
2984         peer->iffval = NULL;
2985         DSA_free(sdsa);
2986         if (temp == 0)
2987                 return (XEVNT_OK);
2988
2989         else
2990                 return (XEVNT_ID);
2991 }
2992
2993
2994 /*
2995  ***********************************************************************
2996  *                                                                     *
2997  * The following routines are used to manipulate certificates          *
2998  *                                                                     *
2999  ***********************************************************************
3000  */
3001 /*
3002  * cert_parse - parse x509 certificate and create info/value structures.
3003  *
3004  * The server certificate includes the version number, issuer name,
3005  * subject name, public key and valid date interval. If the issuer name
3006  * is the same as the subject name, the certificate is self signed and
3007  * valid only if the server is configured as trustable. If the names are
3008  * different, another issuer has signed the server certificate and
3009  * vouched for it. In this case the server certificate is valid if
3010  * verified by the issuer public key.
3011  *
3012  * Returns certificate info/value pointer if valid, NULL if not.
3013  */
3014 struct cert_info *              /* certificate information structure */
3015 cert_parse(
3016         u_char  *asn1cert,      /* X509 certificate */
3017         u_int   len,            /* certificate length */
3018         tstamp_t fstamp         /* filestamp */
3019         )
3020 {
3021         X509    *cert;          /* X509 certificate */
3022         X509_EXTENSION *ext;    /* X509v3 extension */
3023         struct cert_info *ret;  /* certificate info/value */
3024         BIO     *bp;
3025         X509V3_EXT_METHOD *method;
3026         char    pathbuf[MAXFILENAME];
3027         u_char  *uptr;
3028         char    *ptr;
3029         int     temp, cnt, i;
3030
3031         /*
3032          * Decode ASN.1 objects and construct certificate structure.
3033          */
3034         uptr = asn1cert;
3035         if ((cert = d2i_X509(NULL, &uptr, len)) == NULL) {
3036                 msyslog(LOG_ERR, "cert_parse %s\n",
3037                     ERR_error_string(ERR_get_error(), NULL));
3038                 return (NULL);
3039         }
3040
3041         /*
3042          * Extract version, subject name and public key.
3043          */
3044         ret = emalloc(sizeof(struct cert_info));
3045         memset(ret, 0, sizeof(struct cert_info));
3046         if ((ret->pkey = X509_get_pubkey(cert)) == NULL) {
3047                 msyslog(LOG_ERR, "cert_parse %s\n",
3048                     ERR_error_string(ERR_get_error(), NULL));
3049                 cert_free(ret);
3050                 X509_free(cert);
3051                 return (NULL);
3052         }
3053         ret->version = X509_get_version(cert);
3054         X509_NAME_oneline(X509_get_subject_name(cert), pathbuf,
3055             MAXFILENAME - 1);
3056         ptr = strstr(pathbuf, "CN=");
3057         if (ptr == NULL) {
3058                 msyslog(LOG_INFO, "cert_parse: invalid subject %s",
3059                     pathbuf);
3060                 cert_free(ret);
3061                 X509_free(cert);
3062                 return (NULL);
3063         }
3064         ret->subject = emalloc(strlen(ptr) + 1);
3065         strcpy(ret->subject, ptr + 3);
3066
3067         /*
3068          * Extract remaining objects. Note that the NTP serial number is
3069          * the NTP seconds at the time of signing, but this might not be
3070          * the case for other authority. We don't bother to check the
3071          * objects at this time, since the real crunch can happen only
3072          * when the time is valid but not yet certificated.
3073          */
3074         ret->nid = OBJ_obj2nid(cert->cert_info->signature->algorithm);
3075         ret->digest = (const EVP_MD *)EVP_get_digestbynid(ret->nid);
3076         ret->serial =
3077             (u_long)ASN1_INTEGER_get(X509_get_serialNumber(cert));
3078         X509_NAME_oneline(X509_get_issuer_name(cert), pathbuf,
3079             MAXFILENAME);
3080         if ((ptr = strstr(pathbuf, "CN=")) == NULL) {
3081                 msyslog(LOG_INFO, "cert_parse: invalid issuer %s",
3082                     pathbuf);
3083                 cert_free(ret);
3084                 X509_free(cert);
3085                 return (NULL);
3086         }
3087         ret->issuer = emalloc(strlen(ptr) + 1);
3088         strcpy(ret->issuer, ptr + 3);
3089         ret->first = asn2ntp(X509_get_notBefore(cert));
3090         ret->last = asn2ntp(X509_get_notAfter(cert));
3091
3092         /*
3093          * Extract extension fields. These are ad hoc ripoffs of
3094          * currently assigned functions and will certainly be changed
3095          * before prime time.
3096          */
3097         cnt = X509_get_ext_count(cert);
3098         for (i = 0; i < cnt; i++) {
3099                 ext = X509_get_ext(cert, i);
3100                 method = X509V3_EXT_get(ext);
3101                 temp = OBJ_obj2nid(ext->object);
3102                 switch (temp) {
3103
3104                 /*
3105                  * If a key_usage field is present, we decode whether
3106                  * this is a trusted or private certificate. This is
3107                  * dorky; all we want is to compare NIDs, but OpenSSL
3108                  * insists on BIO text strings.
3109                  */
3110                 case NID_ext_key_usage:
3111                         bp = BIO_new(BIO_s_mem());
3112                         X509V3_EXT_print(bp, ext, 0, 0);
3113                         BIO_gets(bp, pathbuf, MAXFILENAME);
3114                         BIO_free(bp);
3115 #if DEBUG
3116                         if (debug)
3117                                 printf("cert_parse: %s: %s\n",
3118                                     OBJ_nid2ln(temp), pathbuf);
3119 #endif
3120                         if (strcmp(pathbuf, "Trust Root") == 0)
3121                                 ret->flags |= CERT_TRUST;
3122                         else if (strcmp(pathbuf, "Private") == 0)
3123                                 ret->flags |= CERT_PRIV;
3124                         break;
3125
3126                 /*
3127                  * If a NID_subject_key_identifier field is present, it
3128                  * contains the GQ public key.
3129                  */
3130                 case NID_subject_key_identifier:
3131                         ret->grplen = ext->value->length - 2;
3132                         ret->grpkey = emalloc(ret->grplen);
3133                         memcpy(ret->grpkey, &ext->value->data[2],
3134                             ret->grplen);
3135                         break;
3136                 }
3137         }
3138
3139         /*
3140          * If certificate is self signed, verify signature.
3141          */
3142         if (strcmp(ret->subject, ret->issuer) == 0) {
3143                 if (!X509_verify(cert, ret->pkey)) {
3144                         msyslog(LOG_INFO,
3145                             "cert_parse: signature not verified %s",
3146                             pathbuf);
3147                         cert_free(ret);
3148                         X509_free(cert);
3149                         return (NULL);
3150                 }
3151         }
3152
3153         /*
3154          * Verify certificate valid times. Note that certificates cannot
3155          * be retroactive.
3156          */
3157         if (ret->first > ret->last || ret->first < fstamp) {
3158                 msyslog(LOG_INFO,
3159                     "cert_parse: invalid certificate %s first %u last %u fstamp %u",
3160                     ret->subject, ret->first, ret->last, fstamp);
3161                 cert_free(ret);
3162                 X509_free(cert);
3163                 return (NULL);
3164         }
3165
3166         /*
3167          * Build the value structure to sign and send later.
3168          */
3169         ret->cert.fstamp = htonl(fstamp);
3170         ret->cert.vallen = htonl(len);
3171         ret->cert.ptr = emalloc(len);
3172         memcpy(ret->cert.ptr, asn1cert, len);
3173 #ifdef DEBUG
3174         if (debug > 1)
3175                 X509_print_fp(stdout, cert);
3176 #endif
3177         X509_free(cert);
3178         return (ret);
3179 }
3180
3181
3182 /*
3183  * cert_sign - sign x509 certificate equest and update value structure.
3184  *
3185  * The certificate request includes a copy of the host certificate,
3186  * which includes the version number, subject name and public key of the
3187  * host. The resulting certificate includes these values plus the
3188  * serial number, issuer name and valid interval of the server. The
3189  * valid interval extends from the current time to the same time one
3190  * year hence. This may extend the life of the signed certificate beyond
3191  * that of the signer certificate.
3192  *
3193  * It is convenient to use the NTP seconds of the current time as the
3194  * serial number. In the value structure the timestamp is the current
3195  * time and the filestamp is taken from the extension field. Note this
3196  * routine is called only when the client clock is synchronized to a
3197  * proventic source, so timestamp comparisons are valid.
3198  *
3199  * The host certificate is valid from the time it was generated for a
3200  * period of one year. A signed certificate is valid from the time of
3201  * signature for a period of one year, but only the host certificate (or
3202  * sign certificate if used) is actually used to encrypt and decrypt
3203  * signatures. The signature trail is built from the client via the
3204  * intermediate servers to the trusted server. Each signature on the
3205  * trail must be valid at the time of signature, but it could happen
3206  * that a signer certificate expire before the signed certificate, which
3207  * remains valid until its expiration. 
3208  *
3209  * Returns
3210  * XEVNT_OK     success
3211  * XEVNT_PUB    bad or missing public key
3212  * XEVNT_CRT    bad or missing certificate
3213  * XEVNT_VFY    certificate not verified
3214  * XEVNT_PER    host certificate expired
3215  */
3216 static int
3217 cert_sign(
3218         struct exten *ep,       /* extension field pointer */
3219         struct value *vp        /* value pointer */
3220         )
3221 {
3222         X509    *req;           /* X509 certificate request */
3223         X509    *cert;          /* X509 certificate */
3224         X509_EXTENSION *ext;    /* certificate extension */
3225         ASN1_INTEGER *serial;   /* serial number */
3226         X509_NAME *subj;        /* distinguished (common) name */
3227         EVP_PKEY *pkey;         /* public key */
3228         EVP_MD_CTX ctx;         /* message digest context */
3229         tstamp_t tstamp;        /* NTP timestamp */
3230         u_int   len;
3231         u_char  *ptr;
3232         int     i, temp;
3233
3234         /*
3235          * Decode ASN.1 objects and construct certificate structure.
3236          * Make sure the system clock is synchronized to a proventic
3237          * source.
3238          */
3239         tstamp = crypto_time();
3240         if (tstamp == 0)
3241                 return (XEVNT_TSP);
3242
3243         if (tstamp < cinfo->first || tstamp > cinfo->last)
3244                 return (XEVNT_PER);
3245
3246         ptr = (u_char *)ep->pkt;
3247         if ((req = d2i_X509(NULL, &ptr, ntohl(ep->vallen))) == NULL) {
3248                 msyslog(LOG_ERR, "cert_sign %s\n",
3249                     ERR_error_string(ERR_get_error(), NULL));
3250                 return (XEVNT_CRT);
3251         }
3252         /*
3253          * Extract public key and check for errors.
3254          */
3255         if ((pkey = X509_get_pubkey(req)) == NULL) {
3256                 msyslog(LOG_ERR, "cert_sign %s\n",
3257                     ERR_error_string(ERR_get_error(), NULL));
3258                 X509_free(req);
3259                 return (XEVNT_PUB);
3260         }
3261
3262         /*
3263          * Generate X509 certificate signed by this server. For this
3264          * purpose the issuer name is the server name. Also copy any
3265          * extensions that might be present.
3266          */
3267         cert = X509_new();
3268         X509_set_version(cert, X509_get_version(req));
3269         serial = ASN1_INTEGER_new();
3270         ASN1_INTEGER_set(serial, tstamp);
3271         X509_set_serialNumber(cert, serial);
3272         X509_gmtime_adj(X509_get_notBefore(cert), 0L);
3273         X509_gmtime_adj(X509_get_notAfter(cert), YEAR);
3274         subj = X509_get_issuer_name(cert);
3275         X509_NAME_add_entry_by_txt(subj, "commonName", MBSTRING_ASC,
3276             (u_char *)sys_hostname, strlen(sys_hostname), -1, 0);
3277         subj = X509_get_subject_name(req);
3278         X509_set_subject_name(cert, subj);
3279         X509_set_pubkey(cert, pkey);
3280         ext = X509_get_ext(req, 0);
3281         temp = X509_get_ext_count(req);
3282         for (i = 0; i < temp; i++) {
3283                 ext = X509_get_ext(req, i);
3284                 X509_add_ext(cert, ext, -1);
3285         }
3286         X509_free(req);
3287
3288         /*
3289          * Sign and verify the certificate.
3290          */
3291         X509_sign(cert, sign_pkey, sign_digest);
3292         if (!X509_verify(cert, sign_pkey)) {
3293                 printf("cert_sign\n%s\n",
3294                     ERR_error_string(ERR_get_error(), NULL));
3295                 X509_free(cert);
3296                 return (XEVNT_VFY);
3297         }
3298         len = i2d_X509(cert, NULL);
3299
3300         /*
3301          * Build and sign the value structure. We have to sign it here,
3302          * since the response has to be returned right away. This is a
3303          * clogging hazard.
3304          */
3305         memset(vp, 0, sizeof(struct value));
3306         vp->tstamp = htonl(tstamp);
3307         vp->fstamp = ep->fstamp;
3308         vp->vallen = htonl(len);
3309         vp->ptr = emalloc(len);
3310         ptr = vp->ptr;
3311         i2d_X509(cert, &ptr);
3312         vp->siglen = 0;
3313         vp->sig = emalloc(sign_siglen);
3314         EVP_SignInit(&ctx, sign_digest);
3315         EVP_SignUpdate(&ctx, (u_char *)vp, 12);
3316         EVP_SignUpdate(&ctx, vp->ptr, len);
3317         if (EVP_SignFinal(&ctx, vp->sig, &len, sign_pkey))
3318                 vp->siglen = htonl(len);
3319 #ifdef DEBUG
3320         if (debug > 1)
3321                 X509_print_fp(stdout, cert);
3322 #endif
3323         X509_free(cert);
3324         return (XEVNT_OK);
3325 }
3326
3327
3328 /*
3329  * cert_valid - verify certificate with given public key
3330  *
3331  * This is pretty ugly, as the certificate has to be verified in the
3332  * OpenSSL X509 structure, not in the DER format in the info/value
3333  * structure.
3334  *
3335  * Returns
3336  * XEVNT_OK     success
3337  * XEVNT_VFY    certificate not verified
3338  */
3339 int
3340 cert_valid(
3341         struct cert_info *cinf, /* certificate information structure */
3342         EVP_PKEY *pkey          /* public key */
3343         )
3344 {
3345         X509    *cert;          /* X509 certificate */
3346         u_char  *ptr;
3347
3348         if (cinf->flags & CERT_SIGN)
3349                 return (XEVNT_OK);
3350
3351         ptr = (u_char *)cinf->cert.ptr;
3352         cert = d2i_X509(NULL, &ptr, ntohl(cinf->cert.vallen));
3353         if (cert == NULL || !X509_verify(cert, pkey))
3354                 return (XEVNT_VFY);
3355
3356         X509_free(cert);
3357         return (XEVNT_OK);
3358 }
3359
3360
3361 /*
3362  * cert - install certificate in certificate list
3363  *
3364  * This routine encodes an extension field into a certificate info/value
3365  * structure. It searches the certificate list for duplicates and
3366  * expunges whichever is older. It then searches the list for other
3367  * certificates that might be verified by this latest one. Finally, it
3368  * inserts this certificate first on the list.
3369  *
3370  * Returns
3371  * XEVNT_OK     success
3372  * XEVNT_FSP    bad or missing filestamp
3373  * XEVNT_CRT    bad or missing certificate 
3374  */
3375 int
3376 cert_install(
3377         struct exten *ep,       /* cert info/value */
3378         struct peer *peer       /* peer structure */
3379         )
3380 {
3381         struct cert_info *cp, *xp, *yp, **zp;
3382
3383         /*
3384          * Parse and validate the signed certificate. If valid,
3385          * construct the info/value structure; otherwise, scamper home.
3386          */
3387         if ((cp = cert_parse((u_char *)ep->pkt, ntohl(ep->vallen),
3388             ntohl(ep->fstamp))) == NULL)
3389                 return (XEVNT_CRT);
3390
3391         /*
3392          * Scan certificate list looking for another certificate with
3393          * the same subject and issuer. If another is found with the
3394          * same or older filestamp, unlink it and return the goodies to
3395          * the heap. If another is found with a later filestamp, discard
3396          * the new one and leave the building.
3397          *
3398          * Make a note to study this issue again. An earlier certificate
3399          * with a long lifetime might be overtaken by a later
3400          * certificate with a short lifetime, thus invalidating the
3401          * earlier signature. However, we gotta find a way to leak old
3402          * stuff from the cache, so we do it anyway. 
3403          */
3404         yp = cp;
3405         zp = &cinfo;
3406         for (xp = cinfo; xp != NULL; xp = xp->link) {
3407                 if (strcmp(cp->subject, xp->subject) == 0 &&
3408                     strcmp(cp->issuer, xp->issuer) == 0) {
3409                         if (ntohl(cp->cert.fstamp) <=
3410                             ntohl(xp->cert.fstamp)) {
3411                                 *zp = xp->link;;
3412                                 cert_free(xp);
3413                         } else {
3414                                 cert_free(cp);
3415                                 return (XEVNT_FSP);
3416                         }
3417                         break;
3418                 }
3419                 zp = &xp->link;
3420         }
3421         yp->link = cinfo;
3422         cinfo = yp;
3423
3424         /*
3425          * Scan the certificate list to see if Y is signed by X. This is
3426          * independent of order.
3427          */
3428         for (yp = cinfo; yp != NULL; yp = yp->link) {
3429                 for (xp = cinfo; xp != NULL; xp = xp->link) {
3430
3431                         /*
3432                          * If the issuer of certificate Y matches the
3433                          * subject of certificate X, verify the
3434                          * signature of Y using the public key of X. If
3435                          * so, X signs Y.
3436                          */
3437                         if (strcmp(yp->issuer, xp->subject) != 0 ||
3438                                 xp->flags & CERT_ERROR)
3439                                 continue;
3440
3441                         if (cert_valid(yp, xp->pkey) != XEVNT_OK) {
3442                                 yp->flags |= CERT_ERROR;
3443                                 continue;
3444                         }
3445
3446                         /*
3447                          * The signature Y is valid only if it begins
3448                          * during the lifetime of X; however, it is not
3449                          * necessarily an error, since some other
3450                          * certificate might sign Y. 
3451                          */
3452                         if (yp->first < xp->first || yp->first >
3453                             xp->last)
3454                                 continue;
3455
3456                         yp->flags |= CERT_SIGN;
3457
3458                         /*
3459                          * If X is trusted, then Y is trusted. Note that
3460                          * we might stumble over a self-signed
3461                          * certificate that is not trusted, at least
3462                          * temporarily. This can happen when a dude
3463                          * first comes up, but has not synchronized the
3464                          * clock and had its certificate signed by its
3465                          * server. In case of broken certificate trail,
3466                          * this might result in a loop that could
3467                          * persist until timeout.
3468                          */
3469                         if (!(xp->flags & (CERT_TRUST | CERT_VALID)))
3470                                 continue;
3471
3472                         yp->flags |= CERT_VALID;
3473
3474                         /*
3475                          * If subject Y matches the server subject name,
3476                          * then Y has completed the certificate trail.
3477                          * Save the group key and light the valid bit.
3478                          */
3479                         if (strcmp(yp->subject, peer->subject) != 0)
3480                                 continue;
3481
3482                         if (yp->grpkey != NULL) {
3483                                 if (peer->grpkey != NULL)
3484                                         BN_free(peer->grpkey);
3485                                 peer->grpkey = BN_bin2bn(yp->grpkey,
3486                                      yp->grplen, NULL);
3487                         }
3488                         peer->crypto |= CRYPTO_FLAG_VALID;
3489
3490                         /*
3491                          * If the server has an an identity scheme,
3492                          * fetch the identity credentials. If not, the
3493                          * identity is verified only by the trusted
3494                          * certificate. The next signature will set the
3495                          * server proventic.
3496                          */
3497                         if (peer->crypto & (CRYPTO_FLAG_GQ |
3498                             CRYPTO_FLAG_IFF | CRYPTO_FLAG_MV))
3499                                 continue;
3500
3501                         peer->crypto |= CRYPTO_FLAG_VRFY;
3502                 }
3503         }
3504
3505         /*
3506          * That was awesome. Now update the timestamps and signatures.
3507          */
3508         crypto_update();
3509         return (XEVNT_OK);
3510 }
3511
3512
3513 /*
3514  * cert_free - free certificate information structure
3515  */
3516 void
3517 cert_free(
3518         struct cert_info *cinf  /* certificate info/value structure */ 
3519         )
3520 {
3521         if (cinf->pkey != NULL)
3522                 EVP_PKEY_free(cinf->pkey);
3523         if (cinf->subject != NULL)
3524                 free(cinf->subject);
3525         if (cinf->issuer != NULL)
3526                 free(cinf->issuer);
3527         if (cinf->grpkey != NULL)
3528                 free(cinf->grpkey);
3529         value_free(&cinf->cert);
3530         free(cinf);
3531 }
3532
3533
3534 /*
3535  ***********************************************************************
3536  *                                                                     *
3537  * The following routines are used only at initialization time         *
3538  *                                                                     *
3539  ***********************************************************************
3540  */
3541 /*
3542  * crypto_key - load cryptographic parameters and keys from files
3543  *
3544  * This routine loads a PEM-encoded public/private key pair and extracts
3545  * the filestamp from the file name.
3546  *
3547  * Returns public key pointer if valid, NULL if not. Side effect updates
3548  * the filestamp if valid.
3549  */
3550 static EVP_PKEY *
3551 crypto_key(
3552         char    *cp,            /* file name */
3553         tstamp_t *fstamp        /* filestamp */
3554         )
3555 {
3556         FILE    *str;           /* file handle */
3557         EVP_PKEY *pkey = NULL;  /* public/private key */
3558         char    filename[MAXFILENAME]; /* name of key file */
3559         char    linkname[MAXFILENAME]; /* filestamp buffer) */
3560         char    statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3561         char    *ptr;
3562
3563         /*
3564          * Open the key file. If the first character of the file name is
3565          * not '/', prepend the keys directory string. If something goes
3566          * wrong, abandon ship.
3567          */
3568         if (*cp == '/')
3569                 strcpy(filename, cp);
3570         else
3571                 snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
3572         str = fopen(filename, "r");
3573         if (str == NULL)
3574                 return (NULL);
3575
3576         /*
3577          * Read the filestamp, which is contained in the first line.
3578          */
3579         if ((ptr = fgets(linkname, MAXFILENAME, str)) == NULL) {
3580                 msyslog(LOG_ERR, "crypto_key: no data %s\n",
3581                     filename);
3582                 (void)fclose(str);
3583                 return (NULL);
3584         }
3585         if ((ptr = strrchr(ptr, '.')) == NULL) {
3586                 msyslog(LOG_ERR, "crypto_key: no filestamp %s\n",
3587                     filename);
3588                 (void)fclose(str);
3589                 return (NULL);
3590         }
3591         if (sscanf(++ptr, "%u", fstamp) != 1) {
3592                 msyslog(LOG_ERR, "crypto_key: invalid timestamp %s\n",
3593                     filename);
3594                 (void)fclose(str);
3595                 return (NULL);
3596         }
3597
3598         /*
3599          * Read and decrypt PEM-encoded private key.
3600          */
3601         pkey = PEM_read_PrivateKey(str, NULL, NULL, passwd);
3602         fclose(str);
3603         if (pkey == NULL) {
3604                 msyslog(LOG_ERR, "crypto_key %s\n",
3605                     ERR_error_string(ERR_get_error(), NULL));
3606                 return (NULL);
3607         }
3608
3609         /*
3610          * Leave tracks in the cryptostats.
3611          */
3612         if ((ptr = strrchr(linkname, '\n')) != NULL)
3613                 *ptr = '\0'; 
3614         snprintf(statstr, NTP_MAXSTRLEN, "%s mod %d", &linkname[2],
3615             EVP_PKEY_size(pkey) * 8);
3616         record_crypto_stats(NULL, statstr);
3617 #ifdef DEBUG
3618         if (debug)
3619                 printf("crypto_key: %s\n", statstr);
3620         if (debug > 1) {
3621                 if (pkey->type == EVP_PKEY_DSA)
3622                         DSA_print_fp(stdout, pkey->pkey.dsa, 0);
3623                 else
3624                         RSA_print_fp(stdout, pkey->pkey.rsa, 0);
3625         }
3626 #endif
3627         return (pkey);
3628 }
3629
3630
3631 /*
3632  * crypto_cert - load certificate from file
3633  *
3634  * This routine loads a X.509 RSA or DSA certificate from a file and
3635  * constructs a info/cert value structure for this machine. The
3636  * structure includes a filestamp extracted from the file name. Later
3637  * the certificate can be sent to another machine by request.
3638  *
3639  * Returns certificate info/value pointer if valid, NULL if not.
3640  */
3641 static struct cert_info *       /* certificate information */
3642 crypto_cert(
3643         char    *cp             /* file name */
3644         )
3645 {
3646         struct cert_info *ret; /* certificate information */
3647         FILE    *str;           /* file handle */
3648         char    filename[MAXFILENAME]; /* name of certificate file */
3649         char    linkname[MAXFILENAME]; /* filestamp buffer */
3650         char    statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3651         tstamp_t fstamp;        /* filestamp */
3652         long    len;
3653         char    *ptr;
3654         char    *name, *header;
3655         u_char  *data;
3656
3657         /*
3658          * Open the certificate file. If the first character of the file
3659          * name is not '/', prepend the keys directory string. If
3660          * something goes wrong, abandon ship.
3661          */
3662         if (*cp == '/')
3663                 strcpy(filename, cp);
3664         else
3665                 snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
3666         str = fopen(filename, "r");
3667         if (str == NULL)
3668                 return (NULL);
3669
3670         /*
3671          * Read the filestamp, which is contained in the first line.
3672          */
3673         if ((ptr = fgets(linkname, MAXFILENAME, str)) == NULL) {
3674                 msyslog(LOG_ERR, "crypto_cert: no data %s\n",
3675                     filename);
3676                 (void)fclose(str);
3677                 return (NULL);
3678         }
3679         if ((ptr = strrchr(ptr, '.')) == NULL) {
3680                 msyslog(LOG_ERR, "crypto_cert: no filestamp %s\n",
3681                     filename);
3682                 (void)fclose(str);
3683                 return (NULL);
3684         }
3685         if (sscanf(++ptr, "%u", &fstamp) != 1) {
3686                 msyslog(LOG_ERR, "crypto_cert: invalid filestamp %s\n",
3687                     filename);
3688                 (void)fclose(str);
3689                 return (NULL);
3690         }
3691
3692         /*
3693          * Read PEM-encoded certificate and install.
3694          */
3695         if (!PEM_read(str, &name, &header, &data, &len)) {
3696                 msyslog(LOG_ERR, "crypto_cert %s\n",
3697                     ERR_error_string(ERR_get_error(), NULL));
3698                 (void)fclose(str);
3699                 return (NULL);
3700         }
3701         free(header);
3702         if (strcmp(name, "CERTIFICATE") !=0) {
3703                 msyslog(LOG_INFO, "crypto_cert: wrong PEM type %s",
3704                     name);
3705                 free(name);
3706                 free(data);
3707                 (void)fclose(str);
3708                 return (NULL);
3709         }
3710         free(name);
3711
3712         /*
3713          * Parse certificate and generate info/value structure.
3714          */
3715         ret = cert_parse(data, len, fstamp);
3716         free(data);
3717         (void)fclose(str);
3718         if (ret == NULL)
3719                 return (NULL);
3720
3721         if ((ptr = strrchr(linkname, '\n')) != NULL)
3722                 *ptr = '\0'; 
3723         snprintf(statstr, NTP_MAXSTRLEN,
3724             "%s 0x%x len %lu", &linkname[2], ret->flags, len);
3725         record_crypto_stats(NULL, statstr);
3726 #ifdef DEBUG
3727         if (debug)
3728                 printf("crypto_cert: %s\n", statstr);
3729 #endif
3730         return (ret);
3731 }
3732
3733
3734 /*
3735  * crypto_tai - load leapseconds table from file
3736  *
3737  * This routine loads the ERTS leapsecond file in NIST text format,
3738  * converts to a value structure and extracts a filestamp from the file
3739  * name. The data are used to establish the TAI offset from UTC, which
3740  * is provided to the kernel if supported. Later the data can be sent to
3741  * another machine on request.
3742  */
3743 static void
3744 crypto_tai(
3745         char    *cp             /* file name */
3746         )
3747 {
3748         FILE    *str;           /* file handle */
3749         char    buf[NTP_MAXSTRLEN];     /* file line buffer */
3750         u_int32 leapsec[MAX_LEAP]; /* NTP time at leaps */
3751         int     offset;         /* offset at leap (s) */
3752         char    filename[MAXFILENAME]; /* name of leapseconds file */
3753         char    linkname[MAXFILENAME]; /* file link (for filestamp) */
3754         char    statstr[NTP_MAXSTRLEN]; /* statistics for filegen */
3755         tstamp_t fstamp;        /* filestamp */
3756         u_int   len;
3757         u_int32 *ptr;
3758         char    *dp;
3759         int     rval, i, j;
3760
3761         /*
3762          * Open the file and discard comment lines. If the first
3763          * character of the file name is not '/', prepend the keys
3764          * directory string. If the file is not found, not to worry; it
3765          * can be retrieved over the net. But, if it is found with
3766          * errors, we crash and burn.
3767          */
3768         if (*cp == '/')
3769                 strcpy(filename, cp);
3770         else
3771                 snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
3772         if ((str = fopen(filename, "r")) == NULL)
3773                 return;
3774
3775         /*
3776          * Extract filestamp if present.
3777          */
3778         rval = readlink(filename, linkname, MAXFILENAME - 1);
3779         if (rval > 0) {
3780                 linkname[rval] = '\0';
3781                 dp = strrchr(linkname, '.');
3782         } else {
3783                 dp = strrchr(filename, '.');
3784         }
3785         if (dp != NULL)
3786                 sscanf(++dp, "%u", &fstamp);
3787         else
3788                 fstamp = 0;
3789         tai_leap.fstamp = htonl(fstamp);
3790
3791         /*
3792          * We are rather paranoid here, since an intruder might cause a
3793          * coredump by infiltrating naughty values. Empty lines and
3794          * comments are ignored. Other lines must begin with two
3795          * integers followed by junk or comments. The first integer is
3796          * the NTP seconds of leap insertion, the second is the offset
3797          * of TAI relative to UTC after that insertion. The second word
3798          * must equal the initial insertion of ten seconds on 1 January
3799          * 1972 plus one second for each succeeding insertion.
3800          */
3801         i = 0;
3802         while (i < MAX_LEAP) {
3803                 dp = fgets(buf, NTP_MAXSTRLEN - 1, str);
3804                 if (dp == NULL)
3805                         break;
3806
3807                 if (strlen(buf) < 1)
3808                         continue;
3809
3810                 if (*buf == '#')
3811                         continue;
3812
3813                 if (sscanf(buf, "%u %d", &leapsec[i], &offset) != 2)
3814                         continue;
3815
3816                 if (i != offset - TAI_1972) 
3817                         break;
3818
3819                 i++;
3820         }
3821         fclose(str);
3822         if (dp != NULL) {
3823                 msyslog(LOG_INFO,
3824                     "crypto_tai: leapseconds file %s error %d", cp,
3825                     rval);
3826                 exit (-1);
3827         }
3828
3829         /*
3830          * The extension field table entries consists of the NTP seconds
3831          * of leap insertion in network byte order.
3832          */
3833         len = i * sizeof(u_int32);
3834         tai_leap.vallen = htonl(len);
3835         ptr = emalloc(len);
3836         tai_leap.ptr = (u_char *)ptr;
3837         for (j = 0; j < i; j++)
3838                 *ptr++ = htonl(leapsec[j]);
3839         crypto_flags |= CRYPTO_FLAG_TAI;
3840         snprintf(statstr, NTP_MAXSTRLEN, "%s fs %u leap %u len %u", cp, fstamp,
3841            leapsec[--j], len);
3842         record_crypto_stats(NULL, statstr);
3843 #ifdef DEBUG
3844         if (debug)
3845                 printf("crypto_tai: %s\n", statstr);
3846 #endif
3847 }
3848
3849
3850 /*
3851  * crypto_setup - load keys, certificate and leapseconds table
3852  *
3853  * This routine loads the public/private host key and certificate. If
3854  * available, it loads the public/private sign key, which defaults to
3855  * the host key, and leapseconds table. The host key must be RSA, but
3856  * the sign key can be either RSA or DSA. In either case, the public key
3857  * on the certificate must agree with the sign key.
3858  */
3859 void
3860 crypto_setup(void)
3861 {
3862         EVP_PKEY *pkey;         /* private/public key pair */
3863         char    filename[MAXFILENAME]; /* file name buffer */
3864         l_fp    seed;           /* crypto PRNG seed as NTP timestamp */
3865         tstamp_t fstamp;        /* filestamp */
3866         tstamp_t sstamp;        /* sign filestamp */
3867         u_int   len, bytes;
3868         u_char  *ptr;
3869
3870         /*
3871          * Initialize structures.
3872          */
3873         if (!crypto_flags)
3874                 return;
3875
3876         gethostname(filename, MAXFILENAME);
3877         bytes = strlen(filename) + 1;
3878         sys_hostname = emalloc(bytes);
3879         memcpy(sys_hostname, filename, bytes);
3880         if (passwd == NULL)
3881                 passwd = sys_hostname;
3882         memset(&hostval, 0, sizeof(hostval));
3883         memset(&pubkey, 0, sizeof(pubkey));
3884         memset(&tai_leap, 0, sizeof(tai_leap));
3885
3886         /*
3887          * Load required random seed file and seed the random number
3888          * generator. Be default, it is found in the user home
3889          * directory. The root home directory may be / or /root,
3890          * depending on the system. Wiggle the contents a bit and write
3891          * it back so the sequence does not repeat when we next restart.
3892          */
3893         ERR_load_crypto_strings();
3894         if (rand_file == NULL) {
3895                 if ((RAND_file_name(filename, MAXFILENAME)) != NULL) {
3896                         rand_file = emalloc(strlen(filename) + 1);
3897                         strcpy(rand_file, filename);
3898                 }
3899         } else if (*rand_file != '/') {
3900                 snprintf(filename, MAXFILENAME, "%s/%s", keysdir,
3901                     rand_file);
3902                 free(rand_file);
3903                 rand_file = emalloc(strlen(filename) + 1);
3904                 strcpy(rand_file, filename);
3905         }
3906         if (rand_file == NULL) {
3907                 msyslog(LOG_ERR,
3908                     "crypto_setup: random seed file not specified");
3909                 exit (-1);
3910         }
3911         if ((bytes = RAND_load_file(rand_file, -1)) == 0) {
3912                 msyslog(LOG_ERR,
3913                     "crypto_setup: random seed file %s not found\n",
3914                     rand_file);
3915                 exit (-1);
3916         }
3917         get_systime(&seed);
3918         RAND_seed(&seed, sizeof(l_fp));
3919         RAND_write_file(rand_file);
3920         OpenSSL_add_all_algorithms();
3921 #ifdef DEBUG
3922         if (debug)
3923                 printf(
3924                     "crypto_setup: OpenSSL version %lx random seed file %s bytes read %d\n",
3925                     SSLeay(), rand_file, bytes);
3926 #endif
3927
3928         /*
3929          * Load required host key from file "ntpkey_host_<hostname>". It
3930          * also becomes the default sign key.
3931          */
3932         if (host_file == NULL) {
3933                 snprintf(filename, MAXFILENAME, "ntpkey_host_%s",
3934                     sys_hostname);
3935                 host_file = emalloc(strlen(filename) + 1);
3936                 strcpy(host_file, filename);
3937         }
3938         pkey = crypto_key(host_file, &fstamp);
3939         if (pkey == NULL) {
3940                 msyslog(LOG_ERR,
3941                     "crypto_setup: host key file %s not found or corrupt",
3942                     host_file);
3943                 exit (-1);
3944         }
3945         host_pkey = pkey;
3946         sign_pkey = pkey;
3947         sstamp = fstamp;
3948         hostval.fstamp = htonl(fstamp);
3949         if (host_pkey->type != EVP_PKEY_RSA) {
3950                 msyslog(LOG_ERR,
3951                     "crypto_setup: host key is not RSA key type");
3952                 exit (-1);
3953         }
3954         hostval.vallen = htonl(strlen(sys_hostname));
3955         hostval.ptr = (u_char *)sys_hostname;
3956         
3957         /*
3958          * Construct public key extension field for agreement scheme.
3959          */
3960         len = i2d_PublicKey(host_pkey, NULL);
3961         ptr = emalloc(len);
3962         pubkey.ptr = ptr;
3963         i2d_PublicKey(host_pkey, &ptr);
3964         pubkey.vallen = htonl(len);
3965         pubkey.fstamp = hostval.fstamp;
3966
3967         /*
3968          * Load optional sign key from file "ntpkey_sign_<hostname>". If
3969          * loaded, it becomes the sign key.
3970          */
3971         if (sign_file == NULL) {
3972                 snprintf(filename, MAXFILENAME, "ntpkey_sign_%s",
3973                     sys_hostname);
3974                 sign_file = emalloc(strlen(filename) + 1);
3975                 strcpy(sign_file, filename);
3976         }
3977         pkey = crypto_key(sign_file, &fstamp);
3978         if (pkey != NULL) {
3979                 sign_pkey = pkey;
3980                 sstamp = fstamp;
3981         }
3982         sign_siglen = EVP_PKEY_size(sign_pkey);
3983
3984         /*
3985          * Load optional IFF parameters from file
3986          * "ntpkey_iff_<hostname>".
3987          */
3988         if (iffpar_file == NULL) {
3989                 snprintf(filename, MAXFILENAME, "ntpkey_iff_%s",
3990                     sys_hostname);
3991                 iffpar_file = emalloc(strlen(filename) + 1);
3992                 strcpy(iffpar_file, filename);
3993         }
3994         iffpar_pkey = crypto_key(iffpar_file, &if_fstamp);
3995         if (iffpar_pkey != NULL)
3996                 crypto_flags |= CRYPTO_FLAG_IFF;
3997
3998         /*
3999          * Load optional GQ parameters from file "ntpkey_gq_<hostname>".
4000          */
4001         if (gqpar_file == NULL) {
4002                 snprintf(filename, MAXFILENAME, "ntpkey_gq_%s",
4003                     sys_hostname);
4004                 gqpar_file = emalloc(strlen(filename) + 1);
4005                 strcpy(gqpar_file, filename);
4006         }
4007         gqpar_pkey = crypto_key(gqpar_file, &gq_fstamp);
4008         if (gqpar_pkey != NULL)
4009                 crypto_flags |= CRYPTO_FLAG_GQ;
4010
4011         /*
4012          * Load optional MV parameters from file "ntpkey_mv_<hostname>".
4013          */
4014         if (mvpar_file == NULL) {
4015                 snprintf(filename, MAXFILENAME, "ntpkey_mv_%s",
4016                     sys_hostname);
4017                 mvpar_file = emalloc(strlen(filename) + 1);
4018                 strcpy(mvpar_file, filename);
4019         }
4020         mvpar_pkey = crypto_key(mvpar_file, &mv_fstamp);
4021         if (mvpar_pkey != NULL)
4022                 crypto_flags |= CRYPTO_FLAG_MV;
4023
4024         /*
4025          * Load required certificate from file "ntpkey_cert_<hostname>".
4026          */
4027         if (cert_file == NULL) {
4028                 snprintf(filename, MAXFILENAME, "ntpkey_cert_%s",
4029                     sys_hostname);
4030                 cert_file = emalloc(strlen(filename) + 1);
4031                 strcpy(cert_file, filename);
4032         }
4033         if ((cinfo = crypto_cert(cert_file)) == NULL) {
4034                 msyslog(LOG_ERR,
4035                     "certificate file %s not found or corrupt",
4036                     cert_file);
4037                 exit (-1);
4038         }
4039
4040         /*
4041          * The subject name must be the same as the host name, unless
4042          * the certificate is private, in which case it may have come
4043          * from another host.
4044          */
4045         if (!(cinfo->flags & CERT_PRIV) && strcmp(cinfo->subject,
4046             sys_hostname) != 0) {
4047                 msyslog(LOG_ERR,
4048                     "crypto_setup: certificate %s not for this host",
4049                     cert_file);
4050                 cert_free(cinfo);
4051                 exit (-1);
4052         }
4053
4054         /*
4055          * It the certificate is trusted, the subject must be the same
4056          * as the issuer, in other words it must be self signed.
4057          */
4058         if (cinfo->flags & CERT_TRUST && strcmp(cinfo->subject,
4059             cinfo->issuer) != 0) {
4060                 if (cert_valid(cinfo, sign_pkey) != XEVNT_OK) {
4061                         msyslog(LOG_ERR,
4062                             "crypto_setup: certificate %s is trusted, but not self signed.",
4063                             cert_file);
4064                         cert_free(cinfo);
4065                         exit (-1);
4066                 }
4067         }
4068         sign_digest = cinfo->digest;
4069         if (cinfo->flags & CERT_PRIV)
4070                 crypto_flags |= CRYPTO_FLAG_PRIV;
4071         crypto_flags |= cinfo->nid << 16;
4072
4073         /*
4074          * Load optional leapseconds table from file "ntpkey_leap". If
4075          * the file is missing or defective, the values can later be
4076          * retrieved from a server.
4077          */
4078         if (leap_file == NULL)
4079                 leap_file = "ntpkey_leap";
4080         crypto_tai(leap_file);
4081 #ifdef DEBUG
4082         if (debug)
4083                 printf(
4084                     "crypto_setup: flags 0x%x host %s signature %s\n",
4085                     crypto_flags, sys_hostname, OBJ_nid2ln(cinfo->nid));
4086 #endif
4087 }
4088
4089
4090 /*
4091  * crypto_config - configure data from crypto configuration command.
4092  */
4093 void
4094 crypto_config(
4095         int     item,           /* configuration item */
4096         char    *cp             /* file name */
4097         )
4098 {
4099         switch (item) {
4100
4101         /*
4102          * Set random seed file name.
4103          */
4104         case CRYPTO_CONF_RAND:
4105                 rand_file = emalloc(strlen(cp) + 1);
4106                 strcpy(rand_file, cp);
4107                 break;
4108
4109         /*
4110          * Set private key password.
4111          */
4112         case CRYPTO_CONF_PW:
4113                 passwd = emalloc(strlen(cp) + 1);
4114                 strcpy(passwd, cp);
4115                 break;
4116
4117         /*
4118          * Set host file name.
4119          */
4120         case CRYPTO_CONF_PRIV:
4121                 host_file = emalloc(strlen(cp) + 1);
4122                 strcpy(host_file, cp);
4123                 break;
4124
4125         /*
4126          * Set sign key file name.
4127          */
4128         case CRYPTO_CONF_SIGN:
4129                 sign_file = emalloc(strlen(cp) + 1);
4130                 strcpy(sign_file, cp);
4131                 break;
4132
4133         /*
4134          * Set iff parameters file name.
4135          */
4136         case CRYPTO_CONF_IFFPAR:
4137                 iffpar_file = emalloc(strlen(cp) + 1);
4138                 strcpy(iffpar_file, cp);
4139                 break;
4140
4141         /*
4142          * Set gq parameters file name.
4143          */
4144         case CRYPTO_CONF_GQPAR:
4145                 gqpar_file = emalloc(strlen(cp) + 1);
4146                 strcpy(gqpar_file, cp);
4147                 break;
4148
4149         /*
4150          * Set mv parameters file name.
4151          */
4152         case CRYPTO_CONF_MVPAR:
4153                 mvpar_file = emalloc(strlen(cp) + 1);
4154                 strcpy(mvpar_file, cp);
4155                 break;
4156
4157         /*
4158          * Set identity scheme.
4159          */
4160         case CRYPTO_CONF_IDENT:
4161                 if (!strcasecmp(cp, "iff"))
4162                         ident_scheme |= CRYPTO_FLAG_IFF;
4163                 else if (!strcasecmp(cp, "gq"))
4164                         ident_scheme |= CRYPTO_FLAG_GQ;
4165                 else if (!strcasecmp(cp, "mv"))
4166                         ident_scheme |= CRYPTO_FLAG_MV;
4167                 break;
4168
4169         /*
4170          * Set certificate file name.
4171          */
4172         case CRYPTO_CONF_CERT:
4173                 cert_file = emalloc(strlen(cp) + 1);
4174                 strcpy(cert_file, cp);
4175                 break;
4176
4177         /*
4178          * Set leapseconds file name.
4179          */
4180         case CRYPTO_CONF_LEAP:
4181                 leap_file = emalloc(strlen(cp) + 1);
4182                 strcpy(leap_file, cp);
4183                 break;
4184         }
4185         crypto_flags |= CRYPTO_FLAG_ENAB;
4186 }
4187 # else
4188 int ntp_crypto_bs_pubkey;
4189 # endif /* OPENSSL */