~ubuntu-branches/debian/squeeze/ntp/squeeze-201010051545

« back to all changes in this revision

Viewing changes to ntpd/ntp_crypto.c

  • Committer: Bazaar Package Importer
  • Author(s): Matt Zimmerman
  • Date: 2004-10-11 16:10:27 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20041011161027-icyjbji8ujym633o
Tags: 1:4.2.0a-10ubuntu2
Use ntp.ubuntulinux.org instead of pool.ntp.org

Show diffs side-by-side

added added

removed removed

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