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