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